【发布时间】:2014-04-10 03:02:04
【问题描述】:
我正在编写一个方法 removeEvens 从列表中删除偶数索引中的值,返回一个新列表,其中包含这些值的原始顺序。交易是我正在实现我自己的链表,我不能使用来自java.util 的链表。
例如,如果变量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;
}
我的输出:
更新的输出:
似乎我已将偶数索引的值存储在新列表 (list2) 中,但我如何将剩余值(奇数索引的值)存储在原始列表 (list1) 中?
【问题讨论】:
标签: java linked-list nodes