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!

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        
        while(curr != null) {
            //缓存next,因为倒叙会改变curr.next
            ListNode next_node = curr.next;
            //将curr.next指向prev,即倒序
            curr.next = prev;
            //之后两步是两次移位。prev移到curr,curr移到下一个
            prev = curr;
            curr = next_node;
        }
        return prev;
    }
}

  

posted @ 2016-01-27 16:29  Ray.Yang  阅读(160)  评论(0编辑  收藏  举报