码迷,mamicode.com
首页 > 其他好文 > 详细

No 206, Reverse Linked List

时间:2016-01-27 17:16:18      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

 

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

标签:

原文地址:http://www.cnblogs.com/Raymond-Yang/p/5163719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!