java - 链表滚动

标签 java linked-list listitem

我正在尝试创建一种方法,将 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] and n = 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,而不是滚动到最后。代码的哪一部分解释了它如何跳过而不在现有列表的每个位置添加新项目?

最佳答案

假设您定义了 headsize 属性;

对于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/

相关文章:

html - 列表项的图像在 html 中重复

java - 将 YUV 网络摄像头图像转换为 java 字节数组

java - 在 Android 中的两个不同 Activity 中安全访问登录数据

Java JTable 排序不适用于一列

c - 在 C 中使用双向链表时出现问题

android - 如何使用 onLongPress 适配器删除列表项

json - UI5 : Dynamically build ListItems from JSON with different Icons

java - 是否可以使用用户的输入来更改数组?

c# - 对象内的链接是否被视为反模式?

c++ - 我怎样才能让这个递归链表反向工作?