python 实现单链表逆序

python 实现单链表逆序

coding=utf-8

节点类

class ListNode(object):
def init(self, x):
self.data = x
self.next = None

链表类

class SingleList(object):
def init(self):
# 初始化头节点
self.head = None

# 头插法添加节点
def add(self, x):
    node = ListNode(x)
    node.next = self.head
    self.head = node
    print(node.data)

# 遍历链表
def travel(self):
    cur = self.head
    while cur is not None:
        print(cur.data, end=' ')
        cur = cur.next

# 尾插法添加节点
def append(self, x):
    node = ListNode(x)
    cur = self.head
    if cur is None:
        self.head = node
    else:
        while cur.next is not None:
            cur = cur.next
        cur.next = node

# (第一种)就地逆序
def reverse(self):
    # 如果链表没有节点或只有一个节点不需要逆序
    if self.head is None or self.head.next is None:
        print("不需要逆序")
    else:
        pre = None  # 前驱节点
        cur = self.head  # 当前节点
        while cur.next is not None:
            # 保留下一个节点
            after = cur.next
            # 将当前节点指向前一个结点
            cur.next = pre
            # 保留当前节点作为下一个节点的前驱节点
            pre = cur
            # 将下一个节点赋值cur, 作为循环
            cur = after
        # 遍历到链表最后一个节点时候,将其指向前驱节点
        cur.next = pre
        #  头节点指向原来链表的最后一个节点
        self.head = cur

# (第二种)插入逆序
def insert_reverse(self):
    cur = self.head  # 当前节点
    pre = None  # 前驱节点
    while cur is not None:
        # 保留下一个节点
        after = cur.next
        # 将头节点指向当前节点
        self.head = cur
        # 将当前节点指向前一个结点
        cur.next = pre
        # 保留当前节点作为下一个节点的前驱节点
        pre = cur
        # 将下一个节点赋值cur, 作为循环
        cur = after

if name == ‘main’:
L = SingleList()
for i in range(1, 11):
L.append(i)
L.travel()
print(’************’)
# L.reverse()

L.insert_reverse()
L.travel()

“C:\Program Files\Python37\python.exe” C:/Users/zhiwei.xiao/PycharmProjects/一般spiderpro/web.py
1 2 3 4 5 6 7 8 9 10 ************
10 9 8 7 6 5 4 3 2 1
Process finished with exit code 0

你可能感兴趣的:(python 实现单链表逆序)