Question
Below is some code of a linked list in java, my addLast method will not work and I have no idea why! when i state
Below is some code of a linked list in java, my addLast method will not work and I have no idea why! when i state that tail.setnext then it should add a pointer to the new node but it does not seem to be doing that, can someone help me. Thanks
package linkedlist;
public class LinkedList {
Node head; Node tail; int size; public LinkedList(){ head = new Node(null); tail = new Node(null); size = 0; } private void addfirst(String data){ if (size == 0){ head = new Node(data); tail = new Node(data); size++; }else{ Node newn = new Node(data); newn.setNext(head); head = newn; size++; } } private void addLast(String data){ if(size == 0){ head = new Node(data); tail = new Node(data); size++; }else{ Node newn = new Node(data); tail.setNext(newn); tail = newn; size++; } // Node current = head; // while(current != null){ // if(current.getNext() == null){ // Node newnn = new Node("test"); // current.setNext(newnn); // size++; // return; // } // current = current.getNext(); // } // } private Node removeLast(){ Node current = head; while(current.getNext() != null){ if(current.getNext() == tail){ Node temp = tail; current.setNext(null); tail = current; return temp; }else{ current = current.getNext(); } } return null; } private Node removei(String data){ if(head.getData() == data){ Node temp = head; head = head.getNext(); return temp; } Node current = head; while(current.getNext() != null){ if(current.getNext().getData() == data){ Node temp = current.getNext(); current.setNext(current.getNext().getNext()); return temp; } current = current.getNext(); } return null; } private void reverse(){ Node current = head; Node previous = null; Node next = null; while(current != null){ next = current.getNext(); current.setNext(previous); previous = current; current = next; } head = previous; }
private void print(){ Node current = head; while (current != null){ System.out.println(current.getData()); current = current.getNext(); } } public static void main(String[] args) { LinkedList l = new LinkedList(); l.addfirst("4"); l.addfirst("3"); l.addfirst("2"); l.addfirst("1"); l.print(); //l.removeLast(); //l.addNodetoend("end"); l.addLast("end"); l.print(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started