首页 > 其他 > 详细

[lintcode easy]Reserve Linked list

时间:2015-11-17 06:48:05      阅读:195      评论:0      收藏:0      [点我收藏+]

Reverse Linked List

Reverse a linked list.

 
 
Example

For linked list 1->2->3, the reversed linked list is 3->2->1

Challenge

Reverse it in-place and in one-pass

 

use two pointer to record the current node and previous node.

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {

ListNode cur=head;
ListNode prev=null;

while(cur!=null)
{
ListNode next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
} }

 

[lintcode easy]Reserve Linked list

原文:http://www.cnblogs.com/kittyamin/p/4970598.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!