java - 删除链表中偶数索引的值

标签 java linked-list nodes

我正在编写一个方法 removeEvens,它从列表中删除偶数索引中的值,返回一个包含这些值的原始顺序的新列表。问题是我正在实现自己的链表,我不能使用 java.util 中的 LinkedList。

例如,如果变量 list1 存储这些值:

**list1: [8, 13, 17, 4, 9, 12, 98, 41, 7, 23, 0, 92]**
And the following call is made:

**LinkedIntList list2 = list1.removeEvens();** 
After the call, list1 and list2 should store the following values:

**list1: [13, 4, 12, 41, 23, 92]
list2: [8, 17, 9, 98, 7, 0]**

方法在这个链表类中:

public class LinkedIntList {
    private ListNode front;   // null for an empty list
    ...
}

ListNode 类的字段:

public int data;          // data stored in this node
public ListNode next;     // link to next node in the list

我的代码(已更新):

public LinkedIntList removeEvens(){
    LinkedIntList b = new LinkedIntList();
    b.front = front;
    if(front == null) {  
        System.out.println("The list inputed it empty");
    }
    else {   
        ListNode even = b.front;
        while(even!=null && even.next!=null ) { 
            int toBeAdded = even.next.data;
            even.next = even.next.next;
            add(toBeAdded);
            even = even.next;
        }
    }
    return b;
}

我的输出:
enter image description here

更新的输出:

enter image description here

似乎我已经将偶数索引的值存储在新列表 (list2) 中,但是如何将剩余的值(奇数索引的)存储在原始列表 (list1) 中?

最佳答案

我假设您的 LinkedIntList 类中有 addTail() 用于在列表末尾添加新节点。

您的代码看起来像这样。还没有尝试过,但应该可以。

public LinkedIntList removeEvens(){
    LinkedIntList b = new LinkedIntList();

    if(front == null) {  
        System.out.println("The list inputed it empty");
    }
    else {   
        ListNode current = front.next; // current node always points to an odd node
        b.addTail(front); // add first node (even) to list
        front = current: // front now points to first odd node.

        // while there is odd node and the next node (even node) is not null
        while(current!=null && current.next != null) { // need to remove even node
                ListNode toBeAdded = current.next; // save the node to be removed
                current.next = current.next.next;
                b.addTail(toBeAdded);
                current = current.next;
        }
    }

    size -= b.size(); // new list size is old list size minus total removed nodes.
    return b;
}

关于java - 删除链表中偶数索引的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22242062/

相关文章:

比较链表 c 中的节点

java - Android中的字节数据类型内存大小

javascript - 从文本 Javascript 创建一个新节点

c - 在一个 block 中定义和声明结构与声明然后定义结构之间是否存在明显差异?

c - 在链接列表的函数中传递指针

c++ - 错误在哪里?

java - 如何使用 LinkedList 更新 HashMap 中的值?

java - 获取错误 "java.lang.NoClassDefFoundError: com.android.tools.fd.runtime.AppInfo"

java - 如何通过Elasticsearch中的嵌套字段计算多个唯一文档?

Java/Swing(以及一般的 GUI)- 使用条件/过滤器构建动态搜索表单的技术或模式