【leetcode踩坑记录】206. 反转链表(Error - Found cycle in the ListNode)

给你单链表的头节点 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;
    }
    
}

在这里插入图片描述

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值