实现单链表的倒置(两种方法)

# conding:utf8
class Node():
    def __init__(self, _item):
        self.item = _item
        self.next = None


class Link():
    def __init__(self):
        self._head = None

    def append(self, _item):
        node = Node(_item)
        cur = self._head
        pre = None
        if cur == None:
            self._head = node
            return
        while cur:
            pre = cur
            cur = cur.next
        pre.next = node

    def travel(self):
        cur = self._head
        while cur:
            print(cur.item)
            cur = cur.next

    # 方式一:三个变量实现单链表倒置
    def reverse1(self):
        pre = None
        cur = self._head
        next_node = cur.next
        while cur:
            cur.next = pre
            pre = cur
            cur = next_node
            if next_node:
                next_node = next_node.next
        self._head = pre

    # 方式二:两个变量实现单链表的倒置
    def reverse2(self):
        pre = None
        cur = self._head
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        self._head = pre


if __name__ == "__main__":
    link = Link()
    link.append(1)
    link.append(2)
    link.append(3)
    link.travel()
    print("---------------------------")
    link.reverse1()
    link.travel()

输出结果:

1
2
3
---------------------------
3
2
1

 

posted @ 2020-05-02 09:26  佛祖让我来巡山  阅读(1644)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网