Leetcode - 206 - Reverse Linked List

本文介绍了如何通过迭代和递归两种方法来实现链表的反转,包括Java、C++和Python的代码示例,并讨论了它们的实现原理和注意事项。

Reverse a singly linked list.

Example:

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

Solutions:

(1) Iterative

We want the curr->next to be prev and in order to iterate in the loop, three elements(prev, curr, nextTemp) need to be updated each time. 

Java:

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}
// https://leetcode.com/problems/reverse-linked-list/solution/

C++:

ListNode* reverseList(ListNode* head) {
        ListNode *prev = NULL, *cur=head, *tmp;
        while(cur){
            tmp = cur->next;
            cur->next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
  }
// by tamugaoqi from https://leetcode.com/problems/reverse-linked-list/discuss/58130/C%2B%2B-Iterative-and-Recursive

Python:

class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
    prev = None
    while head:
        curr = head
        head = head.next
        curr.next = prev
        prev = curr
    return prev
// https://leetcode.com/problems/reverse-linked-list/discuss/58127/Python-Iterative-and-Recursive-Solution

 

(2) Recursive

Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø

Assume from node nk+1 to nm had been reversed and you are at node nk.

n1 → … → nk-1 → nk → nk+1 ← … ← nm

We want nk+1’s next node to point to nk.

So,nk.next.next = nk;

n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2

Java:

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}
// https://leetcode.com/problems/reverse-linked-list/solution/

C++:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !(head -> next)) {
            return head;
        }
        ListNode* node = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return node;
    }
};
// https://leetcode.com/problems/reverse-linked-list/discuss/58130/C%2B%2B-Iterative-and-Recursive

Python:

class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
    return self._reverse(head)

def _reverse(self, node, prev=None):
    if not node:
        return prev
    n = node.next
    node.next = prev
    return self._reverse(n, node)
// https://leetcode.com/problems/reverse-linked-list/discuss/58127/Python-Iterative-and-Recursive-Solution

 

以下是几种 LeetCode 234 题回文链表问题的 Python 实现: ### 方法一:将链表复制到数组里再从两头比对 ```python # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: lst = [] node = head while node: lst.append(node.val) node = node.next start = 0 end = len(lst) - 1 while start < end: if lst[start] != lst[end]: return False start += 1 end -= 1 return True ``` ### 方法二:递归法 ```python # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def isPalindrome(self, head): front_pointer = head def recursively_check(current_node=head): if current_node is not None: if not recursively_check(current_node.next): return False if front_pointer.val != current_node.val: return False nonlocal front_pointer front_pointer = front_pointer.next return True return recursively_check() ``` ### 方法三:快慢指针 + 反转链表 ```python # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: if head is None: return True first_half_end = self.end_of_first_half(head) second_half_start = self.reverse_list(first_half_end.next) result = True first_position = head second_position = second_half_start while result and second_position is not None: if first_position.val != second_position.val: result = False first_position = first_position.next second_position = second_position.next first_half_end.next = self.reverse_list(second_half_start) return result def end_of_first_half(self, head): fast = head slow = head while fast.next is not None and fast.next.next is not None: fast = fast.next.next slow = slow.next return slow def reverse_list(self, head): previous = None current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值