1. 题目
[原题链接]定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:0 <= 节点个数 <= 5000
注意:本题与LeetCode主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/
2. 思路
思路1:双指针
- 定义两个指针: pre 和 cur,注意 pre 最初是指向 null 的。
- 每次让 cur 的 next 指向 pre,实现一次局部反转。
- 局部反转完成之后, 两个指针同时往前移动一个位置。
- 循环上述过程,直至 pre 到达链表尾部。
思路2:递归
递归的两个条件:
- 终止条件是当前节点或者下一个节点 == null
- 在函数内部,改变节点的指向,也就是 head 的下一个节点指向 head
3. 实现
思路1:双指针
# 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:
pre, cur = None, head #定义指针
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
思路2:递归
# 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:
if(head == None or head.next == None): return head
cur = self.reverseList(head.next)
head.next.next = head #head的下一个节点指向head
head.next = None
return cur
4. 其它
- 题目难度:简单
- 相关题目:
- 相关要点:代码的鲁棒性
172万+

被折叠的 条评论
为什么被折叠?



