我正在尝试创建一种方法,将 int 添加到现有链接列表的末尾。
Q: Write a method that takes the head of a list, which is NOT a sentinel node, and an int,
n
. The method should move the first n nodes to the end of the list while keeping them in the same order. For example, if you had a list[1, 3, 5, 7, 9]
andn = 3
, your method should return the list:[7, 9, 1, 3, 5]
(return the head of the modified list).
这是我所拥有的,问题是关于 addLast 方法:
public class ListItem{
public int value;
public ListItem next;
public ListItem(int value, ListItem next){
this.value = value;
this.next = next;
}
public void addFirst(int x){
head = new ListItem(x, head);
size++
}
public void addLast(int x){
if(head == null){
addFirst(x);
}
else{
ListItem p;
for(p = head; p != null; p = p.next){
p.next = new ListItem(x, null);
size++;
}
}
}
我对该方法如何迭代列表有点困惑。在for循环中,它从头部开始,滚动直到没有p.next。但里面的方法看起来像是用新的列表项替换每个 p.next,而不是滚动到最后。代码的哪一部分解释了它如何跳过而不在现有列表的每个位置添加新项目?
最佳答案
假设您定义了 head
和 size
属性;
对于addLast
函数else
部分应如下。
for(p = head; p.next != null; p = p.next);
p.next = new ListItem(x, null);
size++;
关于java - 链表滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423160/