2013-08-12 228 views
0

我使用此刪除方法刪除列表的第3個元素。但它會刪除指定索引之前的所有元素。所以如果Jhon,Sam,Philip,Emma是列表元素,如果我刪除第三元素,那麼剩下的元素就是Nick。我怎樣才能解決這個問題?刪除索引函數刪除索引前的所有元素

import java.util.*; 

class List { 
    Customer listPtr; 
    int index; 

    public void add(Customer customer) { 
     Customer temp = customer; 
     if (listPtr == null) { 
      listPtr = temp; 
      index++; 
     } else { 
      Customer x = listPtr; 
      while (x.next != null) { 
       x = x.next; 
      } 
      x.next = temp; 
      index++; 
     } 
    } 

    public void remove(int index) { 
     int size = size(); 
     Customer tmp = listPtr, tmp2; 
     int i = 0; 
     while (i != size) { 
      if ((i + 1) == index) { 
       tmp2 = tmp; 
       listPtr = tmp2.next; 
       break; 
      } 
      tmp = tmp.next; 
      ++i; 
     } 
    } 

    public int size() { 
     int size = 0; 
     Customer temp = listPtr; 
     while (temp != null) { 
      temp = temp.next; 
      size++; 
     } 
     return size; 
    } 

    public void printList() { 
     Customer temp = listPtr; 
     while (temp != null) { 
      System.out.println(temp); 
      temp = temp.next; 
     } 
    } 
} 

class DemoList { 
    public static void main(String args[]) { 
     List list = new List(); 
     Customer c1 = new Customer("10011", "Jhon"); 
     Customer c2 = new Customer("10012", "Sam"); 
     Customer c3 = new Customer("10013", "Philip"); 
     Customer c4 = new Customer("10014", "Emma");   
     list.add(c1); 
     list.add(c2); 
     list.add(c3); 
     list.add(c4); 
     list.remove(3); 
     System.out.println(list.size()); 
     list.printList(); 
    } 
} 

class Customer { 
    String id; 
    String name; 
    Customer next; 

    public Customer(String id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    public String toString() { 
     return id + " : " + name; 
    } 

    public boolean equals(Object ob) { 
     Customer c = (Customer) ob; 
     return this.id.equals(c.id); 
    } 
} 
+0

誰是尼克?... – NPE

+0

你應該考慮保持跟蹤的大小,而不是每次計算它。這是一個O(n)操作,因此您的列表中的每個方法現在都是O(n)。您在add()上增加的索引應該是大小。 –

回答

0
public void remove(int index) { 
    if (i == 0) { 
     // TODO: do some checks (listPtr is set, has next...) 
     listPtr = listPtr.next; 
    } 
    else { 
     int currentIndex = 0; 
     Customer currentElement = listPtr; 
     while (currentIndex != size()) { 
      if ((currentIndex + 1) == index) { 
       currentElement.next = currentElement.next.next; 
       break; 
      } 
      currentElement = currentElement.next; 
      currentIndex++; 
     } 
    } 
} 
2

remove()方法有幾個問題。

首先,你應該只改變listPtr如果index == 0

在所有其他情況下,您需要調整位置index - 1處節點的node.next

P.S.作爲List的數據成員的index看起來像是一個等待發生的事故。