java - java无限链表问题
问题描述
所以我正在解决这个问题:给定一个排序链表的头部,删除所有重复项,使每个元素只出现一次。返回排序好的链表。测试示例为[1,1,2]。
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode deleteDuplicates(ListNode head) {
ListNode l3=new ListNode(9);
ListNode l4 = l3;
if (head==null||head.next==null){
return head;
}
while (head.next!=null){
if(head.val== head.next.val){
head=head.next;
l3.next=head;
}else {
l3.next=head;
head=head.next;
//when I debug until this line,it will creat infinite list like[1,1,1,1,.......,1,1,1]
}
l3=l3.next;
}
return l4.next;
}
所以正如你在代码中看到的,为什么当测试示例是[1,1,2]时它会创建无限列表?
解决方案
推荐阅读
- datagrid - 控制台应用程序和 DataGrid 之间的 AVALONIA IPC
- c++ - rostest 中的时钟似乎没有在简单测试中运行
- reactjs - 从 React Amplify APP 访问 AWS Secret
- php - 动态调用php数组值以插入同一级别的新数组
- kotlin - kotlin 单元测试没有通过函数
- visual-studio-code - 如何使 Python 变量的 vs 代码建议更加模糊?
- reactjs - validateDOMNesting(...) 反应中的警告
- javascript - 如何在网站上发现 javascript 文件
- vue.js - 如何在 Vue 和 Nuxt.js 项目中添加 Font Awesome?
- facebook-graph-api - 如何为用户已安装的 facebook 应用程序添加新范围?