Reverse Linked List

Easy Reverse Linked ListMy Submissions

37%
Accepted

Reverse a linked list.

Example

For linked list 1->2->3, the reversed linked list is 3->2->1

Challenge Expand 

Reverse it in-place and in one-pass

Tags Expand 


SOLUTION 1 directly distort the direction of the pointer.  BETTER

Oriented the pointer direction to let the current node point to its original previous node. ListNode prev is initialized to Null. At last, we return prev of head is Null.

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }

SOLUTION 2 Let tail.next to be the new Head. 

Add the last to the front. 

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        if (head == null || head.next == null) {
            return head;
        } 
        ListNode tail = head;
        while (tail.next != null) {
            ListNode temp = tail.next.next;
            tail.next.next = head;
            head = tail.next;
            tail.next = temp;
        }
        return head;
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章