35. Reverse Linked List
Reverse a linked list.
Example
Example1:
For linked list 1->2->3
, the reversed linked list is 3->2->1
Example2:
For linked list 1->2->3->4
, the reversed linked list is 4->3->2->1
Challenge
Reverse it in-place and in one-pass
思路:
递归。
1. 定义一个prev成员变量,并初始化为null, 作为反转后链表的头节点
2. 用临时变量保存剩下的(除头结点的)原链表
3. 使取下来的head结点作为反转后链表的头节点(head.next == prev)
4. prev结点指向反转后链表头节点(prev = head)
5. head重新指向剩余链表的头节点。
6. 重复2-6步骤,知道head指向原链表的null位置。
代码:
public ListNode reverse(ListNode head) {
ListNode prev = null; while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}