美文网首页
Day 14 链表反转

Day 14 链表反转

作者: 快乐的老周 | 来源:发表于2020-06-09 07:32 被阅读0次

    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()

    相关文章

      网友评论

          本文标题:Day 14 链表反转

          本文链接:https://www.haomeiwen.com/subject/slyktktx.html