将项目添加到链接列表的末尾

时间:2011-03-08 18:09:25

标签: java linked-list

我正在攻读考试,这是旧考试的一个问题:

我们有一个带有列表头的单链表,其中包含以下声明:

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d;
        next = n;
    }
}

编写一个方法void addLast(Node header, Object x),在列表末尾添加x

我知道如果我真的有这样的话:

LinkedList someList = new LinkedList();

我可以通过以下方式添加项目:

list.addLast(x);

但我怎么能在这里做呢?

9 个答案:

答案 0 :(得分:11)

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d ;
        next = n ;
       }

   public static Node addLast(Node header, Object x) {
       // save the reference to the header so we can return it.
       Node ret = header;

       // check base case, header is null.
       if (header == null) {
           return new Node(x, null);
       }

       // loop until we find the end of the list
       while ((header.next != null)) {
           header = header.next;
       }

       // set the new node to the Object x, next will be null.
       header.next = new Node(x, null);
       return ret;
   }
}

答案 1 :(得分:8)

您希望使用循环浏览整个链接列表并检查每个节点的“下一个”值。最后一个节点将是下一个值为null的节点。只需将此节点的下一个值设为您使用输入数据创建的新节点。

node temp = first; // starts with the first node.

    while (temp.next != null)
    {
       temp = temp.next;
    }

temp.next = new Node(header, x);

这是基本的想法。这当然是伪代码,但它应该足够简单来实现。

答案 2 :(得分:2)

from openpyxl import Workbook
from openpyxl import load_workbook

wb = Workbook()
ws = wb.active
ws['A1'] = 42
ws.append([1, 2, 3])
wb.save('new_document.xlsm')
wb1 = load_workbook('new_document.xlsm')
wb2 = load_workbook('new_document.xlsm', keep_vba=True)
wb2.save('new_document.xlsm')

答案 3 :(得分:1)

以下是链接列表类的部分解决方案,我已将剩余的实现留给您,并且还留下了一个好的建议,即将尾节点添加为链接列表的一部分。

节点文件:

public class Node 
{
    private Object data; 
    private Node next; 

    public Node(Object d) 
    { 
        data = d ;
        next = null;
    }

    public Object GetItem()
    {
        return data;
    }

    public Node GetNext()
    {
        return next;
    }

    public void SetNext(Node toAppend)
    {
        next = toAppend;
    }
}

这是一个链接列表文件:

public class LL
{
    private Node head;

    public LL()
    {
        head = null;
    }

    public void AddToEnd(String x)
    {
        Node current = head;

        // as you mentioned, this is the base case
        if(current == null) {
            head = new Node(x);
            head.SetNext(null);
        }

        // you should understand this part thoroughly :
        // this is the code that traverses the list.
        // the germane thing to see is that when the 
        // link to the next node is null, we are at the 
        // end of the list.
        else {
            while(current.GetNext() != null)
                current = current.GetNext();

            // add new node at the end
        Node toAppend = new Node(x);
            current.SetNext(toAppend);
        }
    }
}

答案 4 :(得分:0)

循环到链接列表的最后一个元素,该元素具有null的下一个指针,然后修改下一个指针以指向一个新节点,该节点具有data = object和next pointer = null

答案 5 :(得分:0)

这是一个提示,你在链表中有一个节点图,你总是保持对headList的引用,这是linkList中的第一个节点。
next指向链表中的下一个节点,因此当next为null时,您位于列表的末尾。

答案 6 :(得分:0)

上述程序可能会给你NullPointerException。这是一种将元素添加到linkedList末尾的更简单方法。

public class LinkedList {
    Node head;

    public static class Node{
        int data;
        Node next;

        Node(int item){
            data = item;
            next = null;
        }
    }
    public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(4);

        ll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;

        ll.printList();
        System.out.println("Add element 100 to the last");
        ll.addLast(100);
        ll.printList();
    }
    public void printList(){
        Node t = head;
        while(n != null){
            System.out.println(t.data);
            t = t.next;
        }

    }

    public void addLast(int item){
        Node new_item = new Node(item);
        if(head == null){
            head = new_item;
            return;
        }
        new_item.next = null;

        Node last = head;
        Node temp = null;
        while(last != null){
            if(last != null)
                temp = last;
            last = last.next;
        }   

        temp.next = new_item;   
        return;
    }
}

答案 7 :(得分:0)

addLast()需要一些优化,因为addLast()中的while循环具有O(n)复杂性。下面是我对LinkedList的实现。使用ll.addLastx(i)运行一次代码并再次使用ll.addLast(i)运行它,您可以看到addLastx()与addLast()的处理时间有很大差异。

Node.java

package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}

LinkedList.java

package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }


    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }


    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}

答案 8 :(得分:0)

如果跟踪尾节点,则无需遍历列表中的每个元素。

您要做的就是更新尾部以指向新节点:

AddValueToListEnd(value) {
    var node = new Node(value);

    if(!this.head) {
        this.head = node;
    } else {
        this.tail.next = node;
    }

    this.tail = node;
}

简而言之:

  • 使用给定值创建一个新节点,并设置tail = null
  • 如果列表为空,则头部和尾部都指向新节点
  • 如果列表不为空,则将旧的tail.next设置为新节点
  • 无论哪种情况,都将尾指针更新为新节点