class Node():
def init(self, val):
self.val = val
self.next = None
class SingleLinkList():
def init(self):
self.head = None
def is_empty(self):
if self.head == None:
return True
def length(self):
cur = self.head
count = 0
while cur != None:
cur = cur.next
count +=1
return count
def travel(self):
cur = self.head
while cur != None:
print(cur.val, end=' ')
cur = cur.next
print('\n')
def append(self, item):
node = Node(item)
cur = self.head
if self.is_empty():
self.head = node
else:
while cur.next != None:
cur = cur.next
cur.next = node
def reverseList(self):
# if self.head == None or self.head.next == None:
# return self.head
pre = None
cur = self.head
while cur != None:
next = cur.next
cur.next = pre
pre = cur
cur = next
self.head = pre
if name == 'main':
sll = SingleLinkList()
sll.append(1)
sll.append(2)
sll.append(3)
sll.append(4)
sll.append(5)
sll.travel()
sll.reverseList()
sll.travel()
网友评论