[lintcode easy]Reserve Linked list

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;
} }

 

posted on 2015-11-17 04:18  一心一念  阅读(135)  评论(0编辑  收藏  举报

导航