问题描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
双指针法
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp;
while (cur != null){
temp= cur.next; // 保存当前结点的后继
cur.next = pre;
// 更新下一次迭代时的指针指向,第一次是指向空
pre = cur;
cur = temp;
}
// 最后一次迭代cur指向空,pre为新头节点
return pre;
头插法(易于理解)
第一种方法将节点的逆向链接放在了下一次迭代,而头插法比较直观,在一轮循环中就完成了局部的逆向链接。
新建一个dummy节点,使用头插法将遍历的节点从头插入,完成倒序。
public static ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode dummy = new ListNode(0, cur);
ListNode temp = null;
while (cur.next!=null){
temp = cur.next;
cur.next = temp.next;
temp.next = dummy.next;
dummy.next = temp;
// cur的下一个节点头插结束
}
// cur节点永远是指向原来链表的第一个节点
return dummy.next;
}