class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class SingleLinkedList(object):
def __init__(self):
'''单链表初始化'''
self.head = None
self.tail = None
def empty(self):
return self.head is None
def length(self):
size = 0
cur = self.head
while cur != None:
size += 1
cur = cur.next
return size
def travel_list(self):
'''遍历整个链表,打印每个节点的数据'''
cur=self.head
while cur is not None:
print(cur.val,end=" ")
cur=cur.next
print("\n")
def headinsert(self,val):
node=Node(val)
if self.head is not None:
node.next=self.head
self.head=node
def rearinsert(self,val):
if self.head is None:
self.headinsert(val)
else:
cur=self.head
while cur.next is not None:
cur=cur.next
cur.next=Node(val)
def insert(self,pos,val):
if pos<=0:
self.headinsert(val)
elif pos>self.length()-1:
self.rearinsert(val)
else:
cur=self.head
count=0
while count<pos-1:
count+=1
cur=cur.next
newest=Node(val)
newest.next=cur.next
cur.next=newest
def del_first(self):
if self.empty():
raise IndexError('链表为空')
if self.length() == 1:
self.head = None
else:
self.head = self.head.next
def del_last(self):
if self.empty():
raise IndexError('链表为空')
if self.length() == 1:
self.tail = None
else:
pre = self.head
cur = pre.next
while cur.next is not None:
pre = cur
cur = cur.next
cur = None
pre.next = None
self.tail = pre
mylist=SingleLinkedList()
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.headinsert(200)
mylist.headinsert(300)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.rearinsert(400)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
print("==========================")
mylist.insert(0,10000)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.insert(10,1000)
mylist.insert(2,500)
mylist.travel_list()
mylist.del_first()
mylist.travel_list()
mylist.del_last()
mylist.travel_list()