Complete Linked List will not Print all Value - java

I think I'm having trouble with my Queue class because I know using a Queue uses the FIFO method, but want to make sure that when I add an element that it is added at the end of the Queue. In my main program I have added numbers 1-4, but when I want to print my entire Queue using the toString method in my Queue class it will only print out the first element which is 1. I would appreciate some help!
Thank you!
public class QuestionFive
{
public static void main(String[] args)
{
// creating a queue
Queue q = new Queue();
// adding numbers 1,2,3 and 4
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
System.out.println(q);
}
}
class Queue
{
//Private Data Member
private Link _head;
//Constructor: A constructor to create an empty Queue,
public Queue()
{
_head = null;
}
//Insert Method: A method to insert a given Object into the Queue.
//Note: We will inserton
public void insert(Object item)
{
Link add = new Link();
add.data = item;
add.next = null;
if(_head == null)
{
_head = add;
}
else
{
for(Link curr = _head; curr.next != null; curr = curr.next)
{
curr.next = add;
}
}
}
//Delete Method: A method to delete an Object from the Queue
public Object delete()
{
if ( _head == null ) return null;
Link prev = null;
Link curr = _head;
while (curr.next != null )
{
prev = curr;
curr = curr.next;
}
if ( prev != null )
{
prev.next = null;
}
else
{
_head = null;
}
return curr.data;
}
// IsEmpty Method: A method to test for an empty Queue
public boolean isEmpty()
{
// queue is empty if front is null
return (_head == null);
}
//toString Method:
public String toString()
{
String s = "";
for (Link curr = _head; curr != null; curr = curr.next)
{
s = s + " " + curr.data;
}
return s;
}
}
//Link Class
class Link
{
public Object data;
public Link next;
}

A much simpler approach is to introduce a tail as well as a head making your queue double-ended, no need to iterate through the entire queue every time you add an item.
class Queue {
private Link head;
private Link tail;
public void insert(Object item) {
Link add = new Link();
add.data = item;
add.next = null;
if(head == null)
{
head = add;
tail = add;
}
else {
tail.next = add;
tail = add;
}
}
}
The method should really be called add since it is appending to the end not inserting.

The logic in your insert() method needs attention. I have modified the else part of the method as follows and it worked:
else
{
for(Link curr = _head; ; curr = curr.next)
{
if(curr.next == null){
curr.next = add;
break;
}
}
}
Here is the full working class:
public class QuestionFive
{
public static void main(String[] args)
{
// creating a queue
Queue q = new Queue();
// adding numbers 1,2,3 and 4
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
System.out.println(q);
}
}
class Queue
{
//Private Data Member
private Link _head;
//Constructor: A constructor to create an empty Queue,
public Queue()
{
_head = null;
}
//Insert Method: A method to insert a given Object into the Queue.
//Note: We will inserton
public void insert(Object item)
{
Link add = new Link();
add.data = item;
add.next = null;
if(_head == null)
{
_head = add;
}
else
{
for(Link curr = _head; ; curr = curr.next)
{
if(curr.next == null){
curr.next = add;
break;
}
}
}
}
//Delete Method: A method to delete an Object from the Queue
public Object delete()
{
if ( _head == null ) return null;
Link prev = null;
Link curr = _head;
while (curr.next != null )
{
prev = curr;
curr = curr.next;
}
if ( prev != null )
{
prev.next = null;
}
else
{
_head = null;
}
return curr.data;
}
// IsEmpty Method: A method to test for an empty Queue
public boolean isEmpty()
{
// queue is empty if front is null
return (_head == null);
}
//toString Method:
public String toString()
{
String s = "";
for (Link curr = _head; curr != null; curr = curr.next)
{
s = s + " " + curr.data;
}
return s;
}
}
//Link Class
class Link
{
public Object data;
public Link next;
}

Fixed in your Code(instead toString method printList):
public class QuestionFive
{
public static void main(String[] args)
{
// creating a queue
Queue q = new Queue();
// adding numbers 1,2,3 and 4
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
q.printList();
System.out.println(q);
}
}
class Queue
{
//Private Data Member
private Link _head;
//Constructor: A constructor to create an empty Queue,
public Queue()
{
_head = null;
}
//Insert Method: A method to insert a given Object into the Queue.
//Note: We will inserton
public void insert(Object item)
{
Link add = new Link();
add.data = item;
add.next = _head;
_head = add;
}
//Prints list data
public void printList() {
Link currentLink = _head;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.next;
}
System.out.println("");
}
//Delete Method: A method to delete an Object from the Queue
public Object delete()
{
if ( _head == null ) return null;
Link prev = null;
Link curr = _head;
while (curr.next != null )
{
prev = curr;
curr = curr.next;
}
if ( prev != null )
{
prev.next = null;
}
else
{
_head = null;
}
return curr.data;
}
// IsEmpty Method: A method to test for an empty Queue
public boolean isEmpty()
{
// queue is empty if front is null
return (_head == null);
}
}
//Link Class
class Link
{
public Object data;
public Link next;
//Print Link data
public void printLink() {
System.out.print("{" + data + "}");
}
}

Related

Removing all instances of an element from a custom LinkedList

Im trying to remove all people from the list who have the same course name in my custom LinkedList class. I have managed to get my programme to delete people individually based on number however can not figure out how to remove multiple at once. I have browsed online for any solutions and have tried multiple so far but none to any success I also attempted one myself but also no success any help or links to were I could learn mode would be greatly appreciated. Below is my Driver, LinkedList, and LinearNode class. I have also removed code I beleive is not relevant to this solution :).
Linked List Class
public class LinkedList<T> implements LinkedListADT<T> {
private int count; // the current number of elements in the list
private LinearNode<T> list; //pointer to the first element
private LinearNode<T> last; //pointer to the last element
//-----------------------------------------------------------------
// Creates an empty list.
//-----------------------------------------------------------------
public LinkedList()
{
this.count = 0;
this.last = null;
this.list = null;
}
public void add (T element)
{
LinearNode<T> node = new LinearNode<T> (element);
if (size() == 0) {
this.last = node; // This is the last and the
this.list = node; // first node
this.count++;
}//end if
else
{
last.setNext(node); // add node to the end of the list
last = node; // now make this the new last node.
this.count++;
} //end else
}
public T remove()
{
LinearNode<T> current = list;
LinearNode<T> temp = list;
T result = null;
if (current == null) {
System.out.println("There are no such employees in the list");
}//end if
else {
result = this.list.getElement();
temp = list;
this.list = this.list.getNext();
temp.setNext(null); //dereference the original first element
count--;
}//end else
return result;
}
public T remove(T element)
{
LinearNode<T> current = list;
LinearNode<T> previous = list;
LinearNode<T> temp;
T result = null;
if (current == null) {
System.out.println("There are no such employees in the list");
}//end if
else {
for (current = this.list; current != null && !current.getElement().equals(element); current = current.getNext())
{
previous = current;
}
if(current == null) {
System.out.println("No such employee on the list");
}
else if (current == list)
{
remove();
}
else if(current == last) {
previous.setNext(null);
this.last = previous.getNext();
count--;
}
else
{
previous.setNext(current.getNext());
count--;
}
}
return result;
}
**
My attempted Solution**
public T clear(T element) {
T result = null;
while (this.list != null && this.list.getElement() == element) {
this.list = this.list.getNext();
count--;
}
if (this.list == null) {
return result;
}
LinearNode<T> current = this.list;
while (current.getNext() != null) {
if (current.getNext().getElement() == element) {
current.setNext(current.getNext());
count--;
} else {
current = current.getNext();
}
}
return result;
}
}
LinearNode Class
public class LinearNode<T>
{
private LinearNode<T> next;
private T element;
//---------------------------------------------------------
// Creates an empty node.
//---------------------------------------------------------
public LinearNode()
{
this.next = null;
this.element = null;
}
//---------------------------------------------------------
// Creates a node storing the specified element.
//---------------------------------------------------------
public LinearNode (T elem)
{
this.next = null;
this.element = elem;
}
//---------------------------------------------------------
// Returns the node that follows this one.
//---------------------------------------------------------
public LinearNode<T> getNext()
{
return this.next;
}
//---------------------------------------------------------
// Sets the node that follows this one.
//---------------------------------------------------------
public void setNext (LinearNode<T> node)
{
this.next = node;
}
//---------------------------------------------------------
// Returns the element stored in this node.
//---------------------------------------------------------
public T getElement()
{
return this.element;
}
//---------------------------------------------------------
// Sets the element stored in this node.
//---------------------------------------------------------
public void setElement (T elem)
{
this.element = elem;
}
}
Driver Class
public class TrainingCourses {
LinkedList<employee>list;
int Size =10;
int numberofEmployees=0;
public TrainingCourses() {
list = new LinkedList<employee>();
inputEmployee();
displayEmployee();
deleteCourses();
displayEmployee();
}
public void inputEmployee() {
employee a;
a = null;
String number,name,courseName = null;
int years;
Scanner scan = new Scanner(System.in);
for (int count = 1; count<=numberofEmployees; count++){
System.out.println("Input employee number");
number = scan.nextLine();
System.out.println("Input employee name");
name = scan.nextLine();
System.out.println("Input years at organisation");
years = scan.nextInt(); scan.nextLine();
if(years >=5) {
System.out.println("Input course name");
courseName = scan.nextLine();
}else {
System.out.println("Can not join training course employee must be with organisation 5 or more years");
}
a = new employee(number,name,years,courseName);
list.add(a);
}
}
public void displayEmployee() {
System.out.println("\nDisplaying all employees....");
System.out.println(list.toString());
}
public void deleteCourses(){
{
Scanner scan = new Scanner(System.in);
employee b = null;
String number,name,courseName;
int years;
System.out.println("Enter employee number you wish to remove");
number = scan.nextLine();
System.out.println("Input employee name");
name = scan.nextLine();
System.out.println("Input years at organisation");
years = scan.nextInt(); scan.nextLine();
System.out.println("Input course name");
courseName = scan.nextLine();
b = new employee(number,name,years,courseName);
list.clear(b);
}
}
public static void main(String[]args) {
new TrainingCourses();
}
}
I don't understand exactly what you want, because of you wrote you want "to remove all people from the list who have the same course name", but your code never checks only property, your code checks equality everywhere.
This example clear function removes all elements equals to param and returns count of removed elements.
public long clear(T element) {
long result = 0L;
LinearNode<T> current = this.list;
LinearNode<T> previous = null;
while (current != null) {
if (current.getElement().equals(element)) {
if (previous != null) {
if (current.getNext() != null) {
previous.setNext(current.getNext());
} else {
this.last = previous;
}
} else if (current.getNext() != null) {
this.list = current.getNext();
} else {
this.list = this.last = null;
}
this.count--;
result++;
} else {
previous = current;
}
current = current.getNext();
}
return result;
}
And after all .equals(..) only true, if the compared Objects has an equals() method and checks its content equality, otherwise two Objects equals by == operator, if they are exactly the same (not by there's contents).

remove the nth value from a doubly linked list in java

oldVal() method this will get to the correct if, else-if, or else statement that is needed to remove the node but then I always get a null point exception I have compared this to similar codes and cannot seem to find what is wrong with it.
please help:
enter code here// ***************************************************************
// DoubleLinked.java
//
// A class using a doubly linked list to represent a list of integers.
//
// ***************************************************************
public class DoubleLinked
{
private int size=0;
private IntNode list;
// ----------------------------------------------
// Constructor -- initializes list
// ----------------------------------------------
public DoubleLinked()
{
list = null;
}
// ----------------------------------------------
// Prints the list elements
// ----------------------------------------------
public void print()
{
for (IntNode temp = list; temp != null; temp = temp.next)
System.out.println(temp.val);
}
// ----------------------------------------------
// Adds new element to front of list
// ----------------------------------------------
public void addToFront(int val)
{
IntNode newNode = new IntNode(val);
newNode.next = list;
if (list != null)
list.prev = newNode;
list = newNode;
size++;
}
public void addToEnd(int val)
{
IntNode newNode = new IntNode(val);
IntNode current;
if (list == null)
{list= newNode;}
else
{
current=list;
while(current.next != null)
current = current.next;
current.next = newNode;
}
size++;
}
public void removeFirst()
{
IntNode test = list;
if (test == null){System.out.println("your list is emty"); size++;}
else if (list != null) { // list might be empty
IntNode temp = list.prev;
if(list.next==null && list.prev==null) {
list=null;
}
else {
list.next.prev = null;
list = list.next;
}
}
size--;
}
public void removeLast()
{
IntNode test = list;
if (test == null){System.out.println("your list is emty"); size++;}
else if(list.next==null && list.prev==null)
{
list=null;
}
else if (list != null){
IntNode current=list;
while(current.next.next != null)
current = current.next;
current.next=null;
}
size--;
}
public void oldVal(int val)
{
IntNode temp=list;
for (int i = 0; i < this.size; i++)
{
if (temp.val != val)
temp= temp.next;
else{
if (temp.prev == null)
{
list=list.next;
}
if (temp.next == null)
{
temp.prev.next=null;
}
else
{
temp.prev.next=temp.next;
temp.next.prev=temp.prev;
}
size--;
break;
}
}}
//***************************************************************
// An inner class that represents a list element.
//***************************************************************
class IntNode
{
public int val;
public IntNode next;
public IntNode prev;
public IntNode(int val)
{
this.val = val;
this.next = null;
this.prev = null;
}
}}

Unable to delete last node in linked list

I trying to delete the last node from my singly-linked list. But I am still unable to resolve this error in code. My deleteFromEnd method is not removing the last node. After calling the delete method, it's still showing the node that I want to delete. The rest of the list is deleted, but the last node itself is not removed. Can you tell me what I am missing, or where the error is?
LinkedList:
package lab5;
public class LinkedList {
public static void main(String argsp[]) {
List ob = new List();
ob.addAtStart("y", 6);
ob.addAtStart("w", 4);
ob.addAtStart("z", 3);
ob.addAtEnd("a", 3);
ob.addAtEnd("b", 4);
ob.addAtEnd("c", 5);
/*
* ob.display(); System.out.println("Deleted first one");
* ob.deleteFromStart();
*/
ob.display();
System.out.println("Deleted End one");
ob.deleteFromEnd();
ob.display();
}
}
List:
package lab5;
public class List {
Node head;
public List() {
head = null;
}
public List(Node e) {
head = e;
}
Node oldfirst = null;
Node lasthead = null;
public void addAtStart(String name, int age) {
Node newObject = new Node(name, age);
newObject.next = head;
if (oldfirst == null) {
oldfirst = newObject;
}
head = newObject;
lasthead = head;
}
public void display() {
Node store = head;
while (store != null) {
store.display();
store = store.next;
System.out.println();
}
}
public void addAtEnd(String name, int age) {
Node atEndValue = new Node(name, age);
oldfirst.next = atEndValue;
oldfirst = atEndValue;
}
public void deleteFromStart() {
if (head.next != null) {
head = head.next;
}
}
public void deleteFromEnd() {
Node start = head;
Node prev = null;
while (head != null) {
prev = head;
head = head.next;
}
prev.next = null;
head = prev;
}
public Node search(String name) {
return head;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return (head.toString()).length();
}
}
Node:
package lab5;
public class Node {
String name;
int age;
Node next;
public Node() {
name = "Abc";
age = 10;
next = null;
}
public Node(String name, int age) {
this.name = name;
this.age = age;
next = null;
}
public void display() {
System.out.println("Name: " + name + " Age: " + age);
}
}
You are modifying head pointer of list which is wrong. Following method worked for me.
public void deleteFromEnd() {
Node start = head;
Node prev = null;
if(start == null || start.next == null)
{
head = null;
return;
}
while (start.next != null) {
prev = start;
start = start.next;
}
prev.next = null;
}
After analysing your code for little more, I found few other issues. You would need to update addAtStart and addAtEnd methods.
Node lasthead = null;
public void addAtStart(String name, int age) {
Node newObject = new Node(name, age);
newObject.next = head;
if(head == null)
lasthead = newObject;
else if(head.next == null)
lasthead = head;
head = newObject;
}
public void addAtEnd(String name, int age) {
Node atEndValue = new Node(name, age);
lasthead.next = atEndValue;
lasthead = atEndValue;
}
The reason being, suppose if I delete a single node from the end of the list. I would not be able to add an element to the end of the list.
When you're deleting from the end of a singly-linked list you have to do things:
Traverse the list, and create a variable to refer to the second-to-last element of your list.
Set the node after the second-to-last node to be null
You should never change the value of head while traversing your linked list, because that effectively deletes the entire list. You have no way of finding your way back to the beginning since you've overwritten your head variable. Instead, iterate using a temporary variable which is initialized as head.
Finally, remember to consider the edge-cases where the list only has 1 element, or is already empty:
public void deleteFromEnd() {
Node current = head;
Node previous = null;
while (current != null && current.next != null) {
previous = current;
current = current.next;
}
if (current == head) {
head = null;
}
if (previous != null) {
previous.next = null;
}
}
Do not change head of Linked List, otherwise you will loose the list.
Try following modification of your function:
public void deleteFromEnd() {
Node start = head;
Node prev = null;
if(start == null){
return;
}
if (start.next == null){
head = null;
return;
}
while (start.next != null) {
prev = start;
start = start.next;
}
prev.next = null;
}

NullPointerException with Linked List (Deleting an element)

I am trying to create a function to delete an element from a linked list. However, I keep getting a NullPointerException. When I run the program, it states:
Exception in thread "main" java.lang.NullPointerException
at ElephantList.delete(ElephantList.java:30)
at BabyElephantWalk.main(BabyElephantWalk.java:15)
How can I delete an element from the linked list without having this exception thrown? Here is the code
BabyElephantWalk.java
public class BabyElephantWalk
{
public static void main (String[] args)
{
ElephantList walk = new ElephantList();
walk.add (new Elephant("Charlie"));
walk.add (new Elephant("Donna"));
walk.add (new Elephant("Chilli"));
walk.add (new Elephant("Piper"));
walk.add (new Elephant("Ziva"));
walk.delete ("Charlie");
System.out.println (walk);
}
}
ElephantList.java
public class ElephantList
{
private ElephantNode head;
private ElephantNode list;
public ElephantList()
{
list = null;
}//end ElephantList constructor
public void add(Elephant cat)
{
ElephantNode node = new ElephantNode(cat);
ElephantNode current;
if (list == null)
list = node;
else
{
current = list;
while (current.next != null)
current = current.next;
current.next = node;
}
}//end add
public void delete(Object x)
{
{
if (head.data == x)
{
head = head.next;
}
else
{
ElephantNode temp = head;
while (temp.next != null)
{
if (temp.next.data.equals(x))
{
temp.next = temp.next.next;
break;
}
else
{
temp = temp.next;
}
}
}
}
}
public String toString ()
{
String result = "";
ElephantNode current = list;
while (current != null)
{
result += current.elephant + "\n";
current = current.next;
}
return result;
}//end toString
private class ElephantNode
{
public Elephant elephant;
public ElephantNode next;
public Object data;
public ElephantNode(Elephant cat)
{
elephant = cat;
next = null;
data = null;
}//end ElephantNode constructor
}//ElephantNode
}//end ElephantList
Elephant.java
public class Elephant
{
private String title;
public Elephant(String newname)
{
title = newname;
}//end Elephant constructor
public String toString ()
{
return title;
}
}
In add method you work with 'list', in delete method you work with 'head'. Retain the only property and work with it:
public void delete(Object x)
{
if (list.data.equals(x)) // <<= 'head' replaced with 'list'; == replaced with .equals
{
list = list.next; // <<= 'head' replaced with 'list'
}
else
{
ElephantNode temp = list; // <<= 'head' replaced with 'list'
while (temp.next != null)
{
if (temp.next.data.equals(x))
{
temp.next = temp.next.next;
break;
}
else
{
temp = temp.next;
}
}
}
}

Java: Singly Linked List, instantiated 4 unique SLLists but adding a value to one list adds the same value to all lists

I'm wondering if this has something to do with how I specified my Singly Linked List class, but the problem is eluding me.
Here is the Singly Linked List class:
class SLList {
private static Node head;
private static long size;
public SLList() {
head = new Node(null, null);
setSize(0);
}
static class Node {
private Object data;
private Node next;
public Node(Object newData, Node n) {
data = newData;
next = n;
}
public Node getNext() {
return next;
}
public void setElement(Object element) {
data = element;
}
public void setNext(Node newNext) {
next = newNext;
}
public String toString() {
String result = data + " ";
return result;
}
public Object getObject() {
return data;
}
}
public Node getHead() {
return head;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public void addLast(Object object) {
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = new Node(object, null);
size++;
}
public void remove(Object object) {
Node pre = head;
Node temp = head.next;
while(temp.next != null) {
pre = temp;
temp = temp.next;
if(temp.data.equals(object)) {
pre = temp.next;
temp = temp.next.next;
size--;
}
}
}
public void printElements() {
Node temp = head;
if(temp.next == null) {
System.out.println("List is empty.");
}
else {
while(temp.next != null) {
temp = temp.next;
System.out.println(temp.data);
}
}
}
}
This is the Set class with a method to add new values to the lists, barring duplicates already in the list:
public class Set {
SLinkedList aList;
SLinkedList bList;
SLinkedList cList;
SLinkedList dList;
public Set() {
aList = new SLinkedList();
bList = new SLinkedList();
cList = new SLinkedList();
dList = new SLinkedList();
}
public SLinkedList getList(char x) {
if(x == 'a') {
return aList;
}
else if(x == 'b') {
return bList;
}
else if(x == 'c') {
return cList;
}
else {
return dList;
}
}
public boolean addElement(SLinkedList list, Object newData) {
SLinkedList.Node newNode = new SLinkedList.Node(newData, null);
SLinkedList.Node traverseNode = list.getHead();
while(traverseNode.getNext() != null) {
traverseNode = traverseNode.getNext();
if(traverseNode.getObject().equals(newNode.getObject())) {
System.out.println("This data is already in the list.");
return false;
}
}
list.addLast(newData);
System.out.println("Node added!");
return true;
}
public void fillList() {
aList.addLast("dog");
aList.addLast(4);
bList.addLast("test");
System.out.println("aList: ");
aList.printElements();
System.out.println("bList: ");
bList.printElements();
}
}
This is the output when I try to use fillList() to add values to the first Singly Linked List, aList
aList:
dog 4 test
bList:
dog 4 test
As you can see, adding values to aList adds the same values to bList. Any help would be greatly appreciated!
This:
private static Node head;
means you have one head for all your instances of SLLIst. So all SLList instance share the same head.
This should be a member of your class, and as such you'll have an instance of head per instance of SLLIst.
e.g.
private Node head;
The same applies to your size field. I don't think you'll need any static members.

Categories

Resources