簡體   English   中英

在單向鏈表中的給定位置和頭部之后刪除節點

[英]Deleting a Node after a given position and head in a singly linked list

我是否錯過了以下代碼中的任何內容。 該代碼是關於從給定其頭部和位置的鏈表中刪除一個節點。 我的程序沒有通過所有的測試用例。

Node Delete(Node head, int position) {

   // Node temp=head;
    int count=1;
    if(position==0){
       head=head.next;
       return head; 
    }
    if(position==1){
        head=head.next.next;
        return head;
    }
    if(position>1){
        Node temp=head;
        while(count<position){
            count++;
            temp=temp.next;
        }
        temp.next=temp.next.next;
    }
    return head;
}

輸入

4

3

1 2 3

0

3

1 2 3

1

3

1 2 3

2

5

4 3 2 5 1

2

我的輸出

23

12 4351

預期輸出

23 13 12 4351

public static Node Delete(Node head, int position) {
           Node node = head;
           Node prevNode = null;
           int index = 0;
        if (head == null && position == 0){
             return head;
           }
         if (head != null && position == 0){
               head = null;
               head = node.next;

           }
           if (position > 0){
           while(index<position){
               prevNode = node;
               node = node.next;
               index = index + 1;
           }
           prevNode.next = node.next;
           node = null;
           }

         return head;
    }

暫無
暫無

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

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