我已经在此页面上搜索了相同的问题,我找到了一个应该有效的解决方案。但我仍然有一个问题,即程序不会删除列表中的第一个元素。在方法remove()head = head.next;应该删除第一个元素。
如果我启动程序,输出为:空列表:[5,7]而不是空列表:[6,7]
有人请问我的元素头或我的实现有什么问题。
public class HeadList {
Entry head;
Entry tail;
public HeadList() {
head = null;
tail = null;
}
public void add(int info) {
Entry p = new Entry(null, null,info);
if(head == null && tail == null){
head = p;
tail = p;
}else{
tail = tail.next = p;
}
}
public int remove(int index) {
Entry p = head;
for(int i=1; i < index; i++) {
p = p.next;
}
if(p.next != null && p.next != head){
int ausgabe = p.elem;
p.next = p.next.next;
return ausgabe;
}else if(index == 0){
int ausgabe = p.elem;
head = head.next;
return ausgabe;
}
else return 0;
}
private void setHead(Entry newHead) {
//TODO
}
public void reverse() {
//TODO
}
public String toString() {
String out = "[";
if (head != null) {
out += head.elem;
Entry tmp = head.next;
while (tmp != null) {
out = out + "," + tmp.elem;
tmp = tmp.next;
}
}
out += "]";
return out;
}
public static void main(String[] args) {
HeadList l = new HeadList();
l.add(5);
l.add(6);
l.add(7);
l.remove(0);
System.out.println("empty list: " + l);
// Test implementation
}
class Entry {
Entry first;
Entry next;
int elem;
public Entry(Entry first, Entry next, int elem) {
this.first = first;
this.next = next;
this.elem = elem;
}
}
}
答案 0 :(得分:0)
我明白了!将remove()
方法中的if-Function更改为(p.next != null && index != 0)