链表翻转

很气人,面试链表反转竟然没写上,耻辱。必须要记录一下。

首先给你nums应该会自己创建链表的吧

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

#创建一个链表
nums = [1,2,3,4,5,6]
tail = head = ListNode(nums[0])
for x in nums[1:]:
    tail.next = ListNode(x) # Create and add another node
    tail = tail.next # Move the tail pointer

  注意下创建的时候tail和head都从第1个元素开始,head不动留着访问用,tail每次都.next链接一个新的

翻转没啥说的,三个变量,pre cur tmp。前中后,前中是全局后是局部。

 #1->2->3 
cur = head
pre = None
while cur:#如果当前有节点
    tmp = cur.next #下个节点
    cur.next = pre #改变方向
    pre = cur#pre前走
    cur = tmp#cur前走
    
print(head.val)

  也不知道为啥就想不起来,可能是面试太紧张了。

posted @ 2021-07-27 20:03  灰人  阅读(29)  评论(0)    收藏  举报