java - 删除链表中的重复项
问题描述
我在java中尝试了以下代码以从链表中删除重复项
public static LinkedListNode<Integer> removeDuplicates(LinkedListNode<Integer> head) {
LinkedListNode<Integer> ptr1=head;
LinkedListNode<Integer> ptr2=head.next;
if(head==null)
return null;
if(head.next==null)
return head;
while(ptr2!=null){
if(ptr1.data==ptr2.data){
ptr2=ptr2.next;
}else{
ptr1.next=ptr2;
ptr1=ptr2;
ptr2=ptr2.next;
}
}
ptr1.next=ptr2;
return head;
}
它将链表的头部作为输入,然后在从中删除重复项后返回头部。
如果我们将以下示例输入用于链表
281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953
它没有按预期删除重复项
ptr1.data == ptr2.data
我尝试在 vscode 中对其进行调试,并惊讶地发现false
当 ptr1 为 386 而 ptr2 在输入的第一个 386 之后为 386 时,我也尝试了 LinkedListNode 的 getter
ptr1.getData()==ptr2.getData()
结果为假
是否有一些与内存分配相关的概念我没有涉及堆或其他东西?
LinkedListNode
如果您对用于在这里创建链表的类和函数感到好奇,它们是:
public class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
LinkedListNode (T data){
this.data=data;
}
T getData(){
return this.data;
}
}
和
static LinkedListNode<Integer> takeinput(){
Scanner sc = new Scanner(System.in);
int data = sc.nextInt();
LinkedListNode<Integer> head = new LinkedListNode<Integer>(data);
LinkedListNode<Integer> tail = head;
data=sc.nextInt();
while(data!=-1){
LinkedListNode<Integer> newNode = new LinkedListNode<Integer>(data);
if(head.next==null){
head.next=newNode;
tail=newNode;
}else{
tail.next=newNode;
tail= newNode;
}
data=sc.nextInt();
}
sc.close();
return head;
}
input:281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953 -1 输入-1后停止接受输入并返回生成链表的头部
解决方案
应该有循环2 While
来选择一个元素并检查. 以下代码可以帮助您更好地理解。element
Linked List
LinkedListNode<Integer> ptr1=head;
LinkedListNode<Integer> ptr2=head.next;
if(head==null)
return null;
if(head.next==null)
return head;
while (ptr1 != NULL && ptr1.next != NULL) // pick 1 element at time
{
ptr2 = ptr1;
while (ptr2.next != NULL)
{
if (ptr1.data == ptr2.next.data) // check if the element exits in LinkedList or not
{
dup = ptr2.next;
ptr2.next = ptr2.next.next;
}
else
ptr2 = ptr2.next;
}
ptr1 = ptr1.next;
}
return head;
推荐阅读
- c# - 是否有模型验证属性可以在不使用自定义代码的情况下检查参数类型?
- css - 带有内部溢出-x 元素的网格模板在 chrome 中中断布局,但在 Firefox 中没有
- c# - Firesharp:执行请求时发生错误。路径:0/,方法:PUT
- php - 将对象对象转换为对象数组(PHP,Laravel)
- java - 每次使用新值启动时如何重置倒数计时器?
- c# - JsonConvert - 强制 MissingMember 为空
- kubernetes - 在 2 节点裸机集群上设置 Rancher Hello World
- javascript - 如何让不同的元素同时响应 - 按下多个按钮同时点亮多个框
- ios - 使用 CoreData 和数组填充表视图部分
- java - zeroDateTimeBehavior=convertToNull 在使用休眠的 jdbc url 中不起作用