Reverse Linked List
Reverse a linked list.
For linked list 1->2->3
, the reversed linked list is 3->2->1
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