《剑指Offer》-- 反转链表(Python)

题目描述:

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路:遍历替换

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None



def ReverseList(pHead):
    if pHead == None or pHead.next==None:
        return pHead

    # 遍历替换法,比容器法快了5倍
    last = None             # 当前节点的上一个节点
    while pHead:
        tmp = pHead.next    # 保存当前节点的下一个节点,不可缺,因为后面更改了当前节点的next指向
        pHead.next = last   # 更改当前节点的next为上一个节点
        last = pHead        # 将上一个节点移动到当前节点
        pHead = tmp         # 当前节点移动到下一个节点

    return last

思路2:容器法

def ReverseListByStack(pHead):
    if pHead == None or pHead.next==None:
        return pHead

    # 容器法
    cur = pHead
    stack = []
    while cur:
        stack.append(cur)
        cur = cur.next

    for i in range(len(stack)-1,-1,-1):
        if i == 0:
            stack[i].next = None
            return stack[-1]
        try:
            stack[i].next = stack[i-1]
        except:
            print('except {}'.format(i))

测试:

a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
f = ListNode(6)
g = ListNode(7)

a.next = b
b.next = c
c.next = d
d.next = e
e.next = f


start = time.time()
Node = ReverseListByStack(a)
print(time.time()-start)

start = time.time()
Node = ReverseList(a)
print(time.time()-start)

while Node:
    print(Node.val)
    Node = Node.next

结果:

容器法时间:6.9141387939453125e-06
遍历替换法:1.1920928955078125e-06
1

 

你可能感兴趣的:(剑指offer)