No 206, Reverse Linked List

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了No 206, Reverse Linked List相关的知识,希望对你有一定的参考价值。

 

Question: Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3

Official Solution: While you are traversing the list, change the current node‘s next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        
        while(curr!=null) {
            ListNode next_node = curr.next;
            curr.next = prev;
            //上两行是反转两个Node
            //下两行是为之后的操作做准备
            prev = curr;
            curr = next_node;
        }
        return prev;
    //本题可以视作反序数组的变形,因为是ListNode,需要引入一个previous。
    }
}

  

以上是关于No 206, Reverse Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 206 Reverse a singly linked list.

[刷题] LeetCode 206 Reverse Linked List

206. Reverse Linked List

Leetcode92. Reverse Linked List II && 206. Reverse Linked List

206. Reverse Linked List

206. Reverse Linked List