反转链表 leetcode206
输入一个链表,反转链表后,输出新链表的表头。
思路
把每个节点的next指向前驱节点pre
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur, pre = head, None # 双指针迭代cur,pre
while cur: # 遍历cur,每次迭代到cur,都将cur.next指向pre,pre和cur后移一位
cur.next, pre, cur = pre, cur, cur.next
return pre # 都迭代完了(cur变成null了),pre就是最后一个节点了