class Node(object):
def __init__(self,elem,next=None):
self.elem=elem
self.next=next
#要支持的操作有1.is_empty()链表是否为空2.length()链表长度3.travel()遍历整个链表4.add(item)链表头部添加元素
#5.append(item)列表尾部添加元素6.insert(pos,item)指定位置添加元素7.remove(删除节点)8.search(item)查找节点是否存在
class SingleLinkList(object):
def __init__(self,node=None):
self.__head=node
def is_empty(self):
return self.__head==None
def length(self):
cur = self.__head
count = 0
while cur!= None:
cur = cur.next
return count
def travel(self):
cur=self.__head
while cur!=None:
print(cur.elem,end=' ')
cur=cur.next
print()
def add(self,item):
node=Node(item)
node.next=self.__head
self.__head=node
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
cur.next=node
def insert(self,pos,item):
if pos<=0:
self.add(item)
elif pos>self.length()-1:
self.append(item)
else:
pre=self.__head
count=0
while count<pos-1:
count+=1
pre=pre.next
node=Node(item)
node.next=pre.next
pre.next=node
def remove(self,item):
cur=self.__head
pre=None
while cur!=None:
if cur.elem==item:
if cur==self.__head:
self.__head=cur.next
else:
pre.next=cur.next
break
else:
pre=cur
cur=cur.next
def search(self,item):
cur=self.__head
while cur!=None:
if cur.elem==item:
return True
else:
cur=cur.next
return False
def reversLinkeList(self):#反转单链表
cur=self.__head
pre=None
next=None
while cur!=None:
next=cur.next
cur.next=pre
pre=cur
cur=next
return pre
if __name__=="__main__":
ll=SingleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
ll.append(2)
ll.add(8)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.travel()#8123456
ll.insert(2,4)
ll.remove(5)
ll.travel()#8142346
print(ll.is_empty())
print(ll.length())
print()
ll.reversLinkeList()
ll.travel()#8
这个链表是 8142346 反转后应该是6432418 但是我的缺输出8 ,改了好久都没改对 求大大们帮帮忙,在原来的基础上看看应该怎么改才能输出正确的反转链表