簡體   English   中英

刪除備用節點:編譯器給我錯誤的答案 idk 為什么

[英]Delete Alternate Nodes: the compiler is getting me wrong answer idk why

給定一個大小為 N 的單鏈表,刪除列表中的所有備用節點。

示例 1:

輸入:鏈表:1->2->3->4->5->6
Output:1->3->5
說明:刪除備用節點
生成具有元素 1->3->5 的鏈表。

我的代碼

class Solution {
    
    public void deleteAlternate (Node head){
        //Write your code here
        Node a = head;
        int i = 0;
        
        while(a!= null){
            if(i%2==0){
                System.out.print(a.data+" ");
            }
            i++;
            a = a.next;
            
        }
        
        System.out.println();
    }
}

我的 output

對於輸入:
6
1 2 3 4 5 6
你的 output 是:
1 3 5
1 2 3 4 5 6

您當前的代碼只是打印列表中奇數位置的所有元素。 但是,您應該修改該列表。 以下是可以執行以從列表中刪除元素“2”的步驟示例:

  • 在元素“1”上時,您會閱讀指向應刪除的下一個元素(元素“2”)的鏈接
  • 您閱讀了從元素“2”到下一個元素“3”的鏈接
  • 您將元素“3”的鏈接保存到元素“1”的“下一個”字段中,所以現在“1”的下一個元素將是“3”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM