简体   繁体   中英

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

Given a Singly Linked List of size N, delete all alternate nodes of the list.

Example 1:

Input: LinkedList: 1->2->3->4->5->6
Output: 1->3->5
Explanation: Deleting alternate nodes
results in the linked list with elements 1->3->5.

my code

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();
    }
}

my output

For Input:
6
1 2 3 4 5 6
your output is:
1 3 5
1 2 3 4 5 6

Your current code is just printing all elements at odd positions in your list. However, you are expected to modify the list. Here is an example of steps which can be performed to remove the element "2" from the list:

  • When on element "1", you read the link to the next element which should be deleted (element "2")
  • You read the link from the element "2" to the next element "3"
  • You save the link to element "3" into the "next" field of the element "1", so now the next element for "1" will be "3".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM