我通过首先使用已排序的元素填充列表来实现已排序的循环链接列表,并且还为其实现了插入和删除功能。但是,在调用delete时,它不会更新列表。我尝试调试delete方法中的代码,但尚未成功。下面是我程序的代码片段。
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;
。
另外,您实际上并没有真正处理空列表的情况,因此请当心!