LeetCode 反转链表
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
按照过程依次翻转。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur_prt = head
done_prt = None
if cur_prt == None:
return head
wait_prt = cur_prt.next
while(wait_prt):
cur_prt.next = done_prt
done_prt = cur_prt
cur_prt = wait_prt
wait_prt = wait_prt.next
cur_prt.next = done_prt
head = cur_prt
return head
还有一种方案就是根据现有的函数进行递归迭代,因为每部都是在上一步翻转的基础上进一步的操作。因为已知reverseList(head)返回翻转后的链表,所以返回reverseList(heed.next)的结果,并对 head.next 进行更新
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
### 递归方法
node = self.reverseList(head.next)
head.next.next = head
head.next = None
return node