Adding items to end of linked list

后端 未结 9 885
夕颜
夕颜 2020-12-03 16:03

I\'m studying for an exam, and this is a problem from an old test:

We have a singly linked list with a list head with the following declaration:

clas         


        
9条回答
  •  难免孤独
    2020-12-03 17:02

    If you keep track of the tail node, you don't need to loop through every element in the list.

    Just update the tail to point to the new node:

    AddValueToListEnd(value) {
        var node = new Node(value);
    
        if(!this.head) {
            this.head = node;
            this.tail = node;
        } else {
            this.tail.next = node; //point old tail to new node
        }
            
        this.tail = node; //now set the new node as the new tail
    }
    

    In plain English:

    • Create a new node with the given value
    • If the list is empty, point head and tail to the new node
    • If the list is not empty, set the old tail.next to be the new node
    • In either case, update the tail pointer to be the new node

提交回复
热议问题