【发布时间】:2017-07-05 23:23:10
【问题描述】:
手动编写 LinkedList 类。几天来一直试图弄清楚这一点。我需要能够从列表中插入和删除节点。插入和删除似乎工作正常,直到列表中有四个或更多节点。在链接了几个节点之后,值开始插入到列表的末尾,然后从那里搞乱所有插入。对于删除,delete 有时会“删除”第一个节点,使第二个节点成为新的头。我看不出错误在哪里。我有实现插入/删除方法的 main 。下面的代码是示例输出,但这里是我的代码:
class SortedLinkedList {
private int size;
private Node head;
public SortedLinkedList() {
size = 0;
head = null;
} //constructor
public Node appropriatePosition(int k) {
Node curr = head;
if(head == null)
return head;
else if(curr.data >= k)
return null;
else if(curr.next == null)
return curr;
else if(curr.next.data > k)
return curr;
while(curr.next != null) { //null? write new if
curr = curr.next;
}
return curr;
}
public void insert(int k) {
Node appPos = appropriatePosition(k);
Node insNode = new Node(k);
if(appPos == null && head != null) {
insNode.next = head;
head = insNode;
}
else if(appPos == null && head == null)
head = insNode;
else {
insNode.next = appPos.next;
appPos.next = insNode;
}
size++;
}
public Node find(int p) {
if(head == null)
return null;
if(head.data == p)
return head;
Node curr = head;
Node prev = null;
while(curr.data != p) {
prev = curr;
curr = curr.next;
if(curr == null)
return null;
else if(curr.data > p) {
System.out.println("Value not found");
return curr;
}
else if(curr == null)
return null;
}
return prev;
}
public void delete(int q) {
Node findVal = find(q);
if(head == null)
System.out.println("Cannot delete: SortedLinkedList is empty");
else if(findVal.data == head.data)
head = head.next;
else if(head.next == null)
System.out.println("Cannot find value");
else if(findVal == null)
System.out.println("Cannot delete: SortedLinkedList is empty");
else if(findVal.data > q)
System.out.println("Value not found");
else {
findVal.next = findVal.next.next;
size--;
}
}
class Node {
public Node next = null;
public int data;
public Node(int k){
data = k;
}
public Node(Node s) {
data = s.data;
next = s;
}
}
插入的示例输出:
插入 输入值:2 打印: 2 插入 输入值:5 打印: 2 5 插入 输入值:5 打印: 2 5 5 插入 输入值:7 打印: 2 5 5 7 插入 输入值:-9 打印: -9 2 5 5 7 插入 输入值:-3 打印: -9 -3 2 5 5 7 插入 输入值:6 打印: -9 -3 2 5 5 7 6 插入 输入值:4 打印: -9 -3 2 5 5 7 6 4 插入 输入值:6 -9 -3 2 5 5 7 6 4 6
删除的示例输出:
删除 输入值:7 打印: -9 -3 2 5 5 6 4 6 删除 输入值:2 打印: -9 -3 5 5 6 4 6 删除 输入值:-3 打印: -3 5 5 6 4 6 删除 输入值:-3 打印: 5 5 6 4 6
【问题讨论】:
-
几个建议:首先,用更有意义的名称命名参数和变量。其次,您的代码中有很多重复。试着摆脱它。第三,请提供一个完整且易于阅读的错误行为示例。
-
感谢您的建议。这些参数只是简单的 int 输入——尽管我可以更有意义地命名它们。输出完成,用户只需输入int进行插入/删除,代码中使用int,然后打印新的LinkedList。我有这么多重复只是因为我试图通过直接解决每个案例来解决这里的问题。这有帮助吗?感谢观看
-
真正有帮助的是您提到的不正确行为的示例。据我所知,您的列表没有完全排序,因为最后您插入了 4 并且它显示为 6 之后的最后一个值。这是您要解决的问题吗?
-
这正是插入的问题。我不知道为什么它会像这样插入到列表的末尾。
标签: java class linked-list