首页 > 其他 > 详细

No 206, Reverse Linked List

时间:2016-01-27 17:15:19      阅读:167      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!