简体   繁体   English

删除备用节点:编译器给我错误的答案 idk 为什么

[英]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.给定一个大小为 N 的单链表,删除列表中的所有备用节点。

Example 1:示例 1:

Input: LinkedList: 1->2->3->4->5->6输入:链表:1->2->3->4->5->6
Output: 1->3->5 Output:1->3->5
Explanation: Deleting alternate nodes说明:删除备用节点
results in the linked list with elements 1->3->5.生成具有元素 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我的 output

For Input:对于输入:
6 6
1 2 3 4 5 6 1 2 3 4 5 6
your output is:你的 output 是:
1 3 5 1 3 5
1 2 3 4 5 6 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:以下是可以执行以从列表中删除元素“2”的步骤示例:

  • When on element "1", you read the link to the next element which should be deleted (element "2")在元素“1”上时,您会阅读指向应删除的下一个元素(元素“2”)的链接
  • You read the link from the element "2" to the next element "3"您阅读了从元素“2”到下一个元素“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".您将元素“3”的链接保存到元素“1”的“下一个”字段中,所以现在“1”的下一个元素将是“3”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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