【发布时间】:2021-03-18 07:30:05
【问题描述】:
我的老师在这个活动中指导我们如何删除双链表的尾部。他创建了一个循序渐进的过程或算法供我们遵循。我跟着它,但它不起作用。或者,也许我追错了。这是算法
检查列表是否为空
- 如果不为空
- 检查列表中是否只有一个节点
- 如果只有一个节点,设置头尾引用为空。
- 如果有多个节点
- 创建一个指向下一个尾部的 temptail (tail.prev)
- 将tail的prev和temptail的next设置为null
- 将 temptail 值分配给尾部
这是我的代码
public void delTail(){
DoubleNode temp;
if(isEmpty()){
return;
}
else if(!isEmpty()){
if(head == tail){
head = tail = null;
}
else{
temp = tail.next;
tail.prev = null;
temp.next = null;
temp = tail;
}
}
}
这是我看到的错误error in my terminal
我认为我是否正确地遵循它?非常感谢您的帮助:)
这是我的构造函数*
public class DoubleNode{
public DoubleNode prev;
public int data;
public DoubleNode next;
public DoubleNode(int d){
this(null, d, null);
}
public DoubleNode(DoubleNode p, int d, DoubleNode n){
prev = p;
data = d;
next = n;
}
}
这是 mt 完整的算子代码*
public class operator{
DoubleNode head;
DoubleNode tail;
DoubleNode laman;
String output = "";
public operator(){
head = tail = null;
}
public boolean isEmpty(){
return head == null;
}
public void addHead(int i){
if(isEmpty()){
head = tail =new DoubleNode(i);
}
else{
head = new DoubleNode(null, i, head);
head.prev = head;
}
}
public void addTail(int i){
DoubleNode last = new DoubleNode(i);
if(isEmpty()){
head = tail = new DoubleNode(i);
}
else{
tail.next = last;
tail = last;
}
}
public void delHead(){
DoubleNode temp = head.next;
if(head==tail){ //this if condition is testing if the head and tail is one only,
head = tail =null; //if there is only one this will set the tail and head to null
}
else{
head = head.next;
head = temp;
}
}
public void delTail(){
DoubleNode temp;
if(isEmpty()) {
return;
}
else {
if(head != tail) {
tail = tail.prev;
temp = tail;
}
else {
head = tail = null;
}
}
}
public void display(){
DoubleNode tmp = head;
output = "<html>";
for(tmp = head; tmp != null; tmp = tmp.next){
output = output + "<br>" + tmp.data + "<b>" + "<br>";
}
output = output + "</html>";
}
}
到目前为止,这是我的全部代码,我有一个带有 jframe 的主类,但我认为它很好,因为我也将它用于单个链接列表。但是我在双链接列表中确实有一个关于删除最后一个节点的问题
【问题讨论】:
-
我的代码有什么问题?您看到了什么错误或问题?
-
代码 sn-p 与伪代码不匹配...在 DLL 中 tail.next 总是为空(记住 tail 在末尾,所以没有下一个)。删除尾部时
tail.prev实际上指向您希望尾部现在的样子.. 所以tail = tail.prev; tail.next = null;似乎就是您所需要的。temp永远不会被使用 - 除非你想保存旧的tail,这样你就可以清除它的“prev”以帮助垃圾收集。 -
我的 if else 条件是否有效?这就是问题所在吗?我尝试了我在这里红色的所有建议,但没有一个有效。
-
请注意,您添加的代码中还有许多其他错误:1) 您有双重分配,例如
head = head.next; head = temp;2) 您并不总是维护prev和next正确。请注意,删除node时,您需要将node.prev.next指向node.next,将node.next.prev指向node.prev。插入node时,您还需要调整引用:node.next = after.next; node.prev = after; node.next.prev = node; after.next = node;(after将是您插入之后的节点)。 -
你还需要考虑当你只有一个节点时你会做什么:
head == tail应该是真的吗?head.next == head和head.prev == head应该是真的吗?如果不是,那么您需要处理这种特殊情况。
标签: java constructor linked-list double tail