2016-12-07 148 views
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; 
     } 
    } 
} 
+0

我明白了!将remove()中的if-Function更改为(p.next!= null && index!= 0) – Philipp

+0

您可以回答自己的问题并将其标记为答案。 – LeHill

回答

0

我明白了!将remove()方法中的if-Function更改为(p.next != null && index != 0)

相关问题