Example
For linked list 1->2->3
, the reversed linked list is 3->2->1
Challenge
Reverse it in-place and in one-pass
值可以改动的话,用双指针,链表保持不变,更新值即可。值不可以改变的话,需要改变链表指针
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
ListNode prev = null;
while(head != null) {
ListNode tmp = head.next;
head.next = prev;
prev = head;
head = tmp;
}
return prev;
}
}