给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解这题的第一想法是,遍历以head结点为头结点的链表,将所有的结点入栈,然后出栈形成一条新链,返回新链即可。(不推荐此做法,时间复杂度很高)
问题描述:
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
Stack<ListNode> stack = new Stack<>(); //利用栈的后进先出
ListNode temp = head;
while (temp.next != null) {
stack.push(temp);
temp = temp.next;
}
stack.push(temp); //将链表的最后一个节点进栈
ListNode resHead = stack.pop();
ListNode tempHead = resHead;
while (!stack.isEmpty()) {
tempHead.next = stack.pop();
tempHead = tempHead.next;
}
return resHead;
}
}
当按如下代码提价测试时,报错Error - Found cycle in the ListNode,将代码调试发现上述代码输出的情况如下显然在val值为1与val值为2的两个结点中形成了环。
原因分析:
题设给出的链val值为1的结点的下一个结点指向val值为2的结点(下面我们简称为1 2 3 4 5 结点)
取栈顶元素为5为新链表的头结点
形成的新链表中
5结点的下一个结点更改为4结点(在题设给的链表中,5结点的下一个结点本为null)
4.next = 3; (题设链表中 4.next = 5)
3.next = 2;
2.next = 1;
若按照上述代码提交 新链表的1.next = 2,仍然指向2结点,故形成了环。
解决方案:
我们仅需当出栈完毕后,将新链表的末尾结点1结点的下一个结点更改会null即可
ListNode resHead = stack.pop();
ListNode tempHead = resHead;
while (!stack.isEmpty()) {
tempHead.next = stack.pop();
tempHead = tempHead.next;
}
tempHead.next = null;
return resHead;
AC代码(不建议采用此方法)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
Stack<ListNode> stack = new Stack<>(); //利用栈的后进先出
ListNode temp = head;
while (temp.next != null) {
stack.push(temp);
temp = temp.next;
}
stack.push(temp); //将链表的最后一个节点进栈
ListNode resHead = stack.pop();
ListNode tempHead = resHead;
while (!stack.isEmpty()) {
tempHead.next = stack.pop();
tempHead = tempHead.next;
}
tempHead.next = null;
return resHead;
}
}