您的位置:首页 > 其它

lintcode-easy-Reverse Linked List

2016-03-06 10:37 375 查看
Reverse a linked list.

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




/**
* 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) {
// write your code here
if(head == null || head.next == null)
return head;

ListNode prev = null;
ListNode curr = head;
ListNode next = head.next;

while(next != null){
curr.next = prev;
prev = curr;
curr = next;
next = next.next;
}
curr.next = prev;

return curr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: