-1

what the difference between methods push() and add() since this ones do the same stuff - push the value into linked list via constructor, but add() doesn't add the value

public class LinkedList {
 
    static class Node {
        int value;
        Node next;
        Node(int value){
            this.value = value;
            next = null;      }
    }; 
    Node head;
    Node next;     
    void push(Node node){
        Node newnode = node;
        newnode.next = head;
        head = newnode;     }     
    void add(Node node, Node head){addNode(node,head);} 
    void addNode(Node node, Node head){     
        Node newnode = node;
        newnode.next = head;
        head = newnode;     }     
    /* Function to print linked list */
    void printlist(Node head){                 
          while(head != null){
              System.out.println(head.value + " ");
              head = head.next; }    
              }
 
    // Driver program to test above functions
    public static void main(String args[])
    {
        LinkedList list = new LinkedList();
        list.head = null;
        list.head = new Node(5);
        list.push(new Node(6));
        list.add(new Node(3), list.head); 
        list.push(new Node(7));        
        list.printlist(list.head);            
    }
}


demsee
  • 53
  • 9

1 Answers1

1

Your add method, or more correctly, addNode method, is not doing anything to the instance.

It is effectively assigning the parameter head to, the next value of parameter, node.

void addNode(Node node, Node head) {
    node.next = head;
}

The push method is correct, it will stack the object before the instance's head node.

You can remove the the addNode method, and for the add method, it only requires 1 parameter.

You'll want to locate the last node in the structure, and then append the parameter to it.

void add(Node node) {
    Node lastNode = this.head;
    while (lastNode.next != null) lastNode = lastNode.next;
    lastNode.next = node;
}
Reilas
  • 3,297
  • 2
  • 4
  • 17