[LeetCode 206] Reverse Linked List

Reverse a singly linked list.

solution: 

1. Iteration: 

two pointers go through linked list, reverse two neigbour list node. 

2. Recursion


public ListNode reverseList(ListNode head) {
        ListNode p1 = head;
        if(head == null || head.next == null) return head;
        ListNode p2 = head.next;
        while(p2!=null){
            ListNode p3 = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = p3;
        }
        head.next = null;
        return p1;
    }

public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return head;
        ListNode secondElem = head.next;
        head.next = null;
        //reverse everything from the second element on
        ListNode reverseRest = reverseList(secondElem);
        //join the two lists
        secondElem.next = head;
        return reverseRest;
    }


你可能感兴趣的:(LinkedList)