gpt4 book ai didi

java - 删除元素后排序循环链表未更新?

转载 作者:行者123 更新时间:2023-11-30 08:00:15 25 4
gpt4 key购买 nike

我正在实现一个排序的循环链表,首先用排序的元素填充列表,并为其实现插入和删除功能。但是,在调用删除时,它不会更新列表。我尝试在删除方法中调试代码,但尚未成功。下面是我的程序的代码片段。

class CNode {
public int data;
public CNode next;

public CNode() {
this.data = 0;
this.next = null;
}

public CNode(int data, CNode next) {
this.data = data;
this.next = next;
}

public CNode(int data) {
this.data = data;
this.next = null;
}
}

以及驱动程序类 -

public class SortedCLL {
public static CNode head = new CNode();
public static CNode last = new CNode();
public static int NoN;

public SortedCLL() {
int N = 3;
int val[] = {4, 2, 6};
Arrays.sort(val);
CNode first = new CNode(val[0]);
head.next = first;
last.next = first;
NoN++;

for (int i = 1; i < N; i++) {
CNode n = new CNode(val[i]);
last.next.next = n;
last.next = n;
n.next = head.next;
NoN++;
}

//DELETING AN ELEMENT
delete(2);

//INSERTING AN ELEMENT
insert(7);

CNode check = head.next;
for (int i = 0; i < NoN; i++) {
System.out.print(check.data + " ");
check = check.next;
}

}

public static void main(String args[]) throws Exception {
new SortedCLL();
}

private void insert(int element) {
CNode n = new CNode(element);
if(element < head.next.data) {
n.next = head.next;
head.next = n;
last.next.next = n;
NoN++;
return;
}
int nodes = NoN - 1;
CNode iter = head;
while(nodes-- > 0){
if(iter.data < element && iter.next.data > element) {
n.next = iter.next;
iter.next = n;
NoN++;
return;
}
}
last.next.next = n;
last.next = n;
n.next = head.next;
NoN++;
return;
}

private void delete(int element) {
//System.out.println( " : " +element);
CNode prev = last.next;
CNode iter = head.next;
int nodes = NoN;
while(nodes-- > 0) {
if(iter.data == element) {
//HERE IT IS PRINTING CORRECT PREV AND NEXT NODE'S DATA.
System.out.println( prev.data + " : " +iter.next.data);
prev.next = iter.next;
NoN--;
return;
}
prev = iter;
iter = iter.next;
}
return;
}

}

检查SortedCLL类中的调试语句,在delete方法中,它打印了正确的prev和next值,但输出仍然不符合预期。

expected list

4 6 7

program's list

2 4 6 7

任何帮助表示赞赏!

最佳答案

您忘记了删除列表头部的边缘情况,需要在删除时执行 head = head.next;

此外,您并没有真正处理任何地方的空列表的情况,所以要小心!

关于java - 删除元素后排序循环链表未更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32067210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com