Adding items to end of linked list

后端 未结 9 763
夕颜
夕颜 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 16:58

    loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null

    0 讨论(0)
  • 2020-12-03 16:58

    The above programs might give you NullPointerException. This is an easier way to add an element to the end of 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;
        }
    }
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题