简体   繁体   English

将LinkedList插入另一个LinkedList

[英]Inserting a LinkedList into another LinkedList

At the moment, I have a method in my LinkedList (not the Java's one) class that adds single nodes to a LinkedList and it looks like this: 目前,我在LinkedList(不是Java的类)类中有一个方法,可以将单个节点添加到LinkedList中,如下所示:

  public void add(int index, T v) {
     if(isValidIntervalPosition(index)) {
        Node<T> n = new Node<T>(v);
        if(index == 0) {
           n.setNext(head);
           head = n;
        }
        else {
           Node<T> m = head;
           int count = 1;
           while(count < index) {
              m = m.getNext();
              count++;
           }

           n.setNext(m.getNext());
           m.setNext(n);
        } 

        sz++;
     }
  }

But I would like to implement another method that adds the nodes from an input LinkedList to the current LinkedList. 但是我想实现另一种方法,将节点从输入LinkedList添加到当前LinkedList。

Here is the skeleton: 这是骨架:

 public void add(int position, LinkedList<T> list) {


 }

I've been playing with it for a few hours with no result. 我已经玩了几个小时,没有结果。 How would I go about doing this if I already can insert single nodes? 如果我已经可以插入单个节点,该怎么办?

Try: 尝试:

public void add(int position, LinkedList<T> list) {
    int index = position;
    for(T elem : list) {
        add(index ++, elem) // call to your implementation + increment index
    }
}

I think you can simply do 我想你可以做

public void add(int position, final LinkedList<T> list) {
    for(int i = 0; i < list.size(); i++) {
        add(position++, list.get(i));
    }
}

What you want to do is NOT to touch every single node of the list to add. 您要做的是不要触摸列表中的每个要添加的节点。 Instead, to insert list between nodes u and v you make u.next point at list.head and list.tail.next (the last element, I don't know if you store list.tail it or have to iterate through all nodes of list to get it) point at v (the old u.next ) 相反,要在节点uv之间插入list ,请使u.next指向list.headlist.tail.next (最后一个元素,我不知道您是否存储list.tail还是必须遍历所有节点要获取它的list )指向v (旧的u.next

It is hard to write a code example without knowing the details of your list class (ie which members and methods there are). 如果不知道列表类的详细信息(即存在哪些成员和方法),就很难编写代码示例。

Especially, since implementing your own LinkedList is seldomly useful for your program but usually an exercise for data structures, this is the most important thing to get about the "add a whole list" exercise. 特别是,由于实现自己的LinkedList对您的程序很少有用,但通常是对数据结构的练习,因此这是“添加整个列表”练习中最重要的事情。

Here first get the size of existing list and then add to the current position 这里首先获取现有列表的大小,然后添加到当前位置

 public static void add(int position, LinkedList<String> list) {
      System.err.println(list.size());
      list.add(list.size(), "aaa");
      System.out.println(list.get(1));

     }

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

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