0
我已經在此頁面上搜索了相同的問題,並找到了應該工作的解決方案。但我仍然有問題,程序不會刪除列表中的第一個元素。在方法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;
}
}
}
我明白了!將remove()中的if-Function更改爲(p.next!= null && index!= 0) – Philipp
您可以回答自己的問題並將其標記爲答案。 – LeHill