[LC 206]. Reverse Linked List

两种方法:Iteration 和 recursion。
Iteration:
1 ——–> 2 ——–> 3
newhead head temp

    public ListNode reverseList(ListNode head) {
        ListNode newhead = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = newhead;
            newhead = head;
            head = temp;
        }
        return newhead;
    }

Recursion:同样是顺序的反转

    public ListNode reverseList(ListNode head) {
        return reverse(head, null);
    }
    
    private ListNode reverse(ListNode head, ListNode newhead) {
        if (head == null) return newhead;
        ListNode next = head.next;
        head.next = newhead;
        return reverse(next, head);
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s