206. Reverse Linked List
Easy
210659FavoriteShare
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* 就地翻转法
* 把当前链表的下一个节点pCur插入到头结点dummy的下一个节点中,就地反转。
* dummy->1->2->3->4->5的就地反转过程:
* dummy->2->1->3->4->5
* dummy->3->2->1->4->5
* dummy->4>-3->2->1->5
* dummy->5->4->3->2->1
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse1(ListNode head) {
//空链表
if (head == null)
return head;
ListNode dummy = new ListNode(-1);
//将dummy放在当前列表最前面 dummy->1->2->3->4->5
dummy.next = head;
ListNode prev = dummy.next;//1
ListNode pCur = prev.next;//2
while (pCur != null) {
//dummy->1->3->4->5 2->3->4->5
prev.next = pCur.next;
//2->1->3->4->5 dummy->1->3->4->5
pCur.next = dummy.next;
//dummy->2->1->3->4->5
dummy.next = pCur;
//pCur=3 继续循环
pCur = prev.next;
}
return dummy.next;
}
/**
* 新建链表,头节点插入法
* 思路:新建一个头结点,遍历原链表,把每个节点用头结点插入到新建链表中。最后,新建的链表就是反转后的链表。
* 过程
* pCur是要插入到新链表的节点。 pNex是临时保存的pCur的next。
* pNex保存下一次要插入的节点 把pCur插入到dummy中 纠正头结点dummy的指向 pCur指向下一次要插入的节点
* 循环条件 pCur is not null
* @param head
* @return
*/
public ListNode reverse2(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode pCur = head;
while (pCur != null) {
ListNode pNex = pCur.next;
pCur.next = dummy.next;
dummy.next = pCur;
pCur = pNex;
}
return dummy.next;
}