2016-11-23 68 views
-1

我面臨着參考操作的問題: 首先這是一個代碼,其值爲x並遍歷List,刪除任何具有小於或等於X值的鏈接,但它給了我一個不規則的輸出。幫助被讚賞。單鏈表參考操作

public void rlx (int x){ 
     Link p = head;//Initializing a pointer equal to head 
     for (Link c = head.next; c!=null;c=c.next) {//Initializing another Pointer with the Condition to termination 
      if((int)head.data<=x){//If the Value of head< = to X 
       head=head.next;//Skip the first and assign head to the second 
      }else if((int)c.data<=x){ 
       p.next=c.next;//P.next skip c by pointing to c.next instead of c; 
      } 
      p=c; reinitialize p; 
     } 

    } 

主要方法:

public static void main(String [] args){ 
    LinkList l = new LinkList(); 
    l.insertLast(1); 
    l.insertLast(2); 
    l.insertLast(3); 
    l.insertLast(4); 
    l.insertLast(3); 
    l.insertLast(2); 
    l.insertLast(1); 
    l.rlx(3); 
    System.out.print(l); 
} 

輸出:[4,2]

+0

我們需要更多信息才能開始診斷正在發生的事情。從我看來,你*可能*也有數據插入的問題。 – Makoto

+0

我認爲問題是數據刪除,因爲輸出Result應該是[4],因爲所有其他值都等於或小於x。我希望我可以做到這一點,而不使用其他鏈接列表。注意這個類是由我自己製作的,這個方法是內部的。@ Makoto –

回答

0

你的算法有很多的問題,我真的不知道從哪裏開始。首先,你不應該在每次循環迭代時檢查頭部,你應該只檢查c.data < = x。其次,只需將前一個指針指向後面的節點,就不會從單個鏈接列表中刪除節點。如果c.data> x不是每次迭代都應該設置p = c。我一般都反對這樣做的人的作業規則,但在這裏

public void rlx (int x){ 
    While(head != null && (int)head.data <= x) { 
     head = head.next 
    } 
    Link p = head;//Initializing a pointer equal to head 
    for (Link c = head.next; c!=null;c=c.next) {//Initializing another Pointer with the Condition to termination 
     if((int)c.data<=x){ 
      p.next=c.next;//P.next skip c by pointing to c.next instead of c; 
     } 
     Else { 
      p=c; 
     } 
    } 
} 

我沒有打擾來測試,因爲它基本上是僞代碼,我假設你的鏈接類型是一個指針對象。基本上,你需要明確地做垃圾收集,但更重要的是,你應該刪除頭部,直到在while循環中找到一個大於x的值,然後使用單獨的for循環來刪除頭部之後的值。否則,如果頭部小於x,c小於x,則會移除頭部,然後變爲c,但由於p仍然是舊頭部,因此您會更新列表,以便舊頭部指向下一個值是沒有意義的,因爲沒有指向p並且你當前的頭將是不大於x的c。那麼,p將變成c,它不大於x。 p只應該指向最近發現的大於x的鏈接,並且只有在找到鏈接大於x的鏈接後纔會被替換。

+0

非常感謝。 –