I'm using a generic linked list to implement priority queue where I use the comparable function for the insert function where it finds a slot where it's size is bigger than the current node. I have problem actually getting the add function insert the elements according priority queue requirements. The priority queue should go from smallest to biggest.
Edit: I realize the problem lies with inserting a number bigger than the head. During add 11, the function only compares with 5 and add it after 5 which ruins the sequence.
Current output
PQ: 5
PQ: 5,10
PQ: 5,9,10
PQ: 5,11,9,10
PQ: 5,7,11,9,10
PQ: 2,5,7,11,9,10
Desired output
PQ: 2,5,7,9,10,11
My add function
public class PQLinkedList<T extends Comparable<T>>{
private class Node{
private T data;
private Node next;
// Constructor that takes in data to input for the node
public Node(T data) {
this.data = data;
this.next = null;
}
}
private int length = 0;
private Node head;
int cmp = 0;
public PQLinkedList() {
head = null;
}
//Compare with each element till it finds a suitable position to insert itself
//Ascending order
//INCOMPLETE
//Compare part of this code is not complete!
public void addPQ( T data) {
Node node = new Node(data);
Node temp2 = null;
if ( head == null) {
addFirst(data);
}
else {
Node curr = head;
int count = getSize();
while ( count != 0) {
cmp = data.compareTo(curr.data);
if ( cmp < 0 ) {
addFirst(data);
break;
}
else if (cmp>=0 ){
if ( curr.next == null) {
curr.next = node;
break;
}
// if there curr.next is not empty
// Move all the nodes towards to tail by 1
else {
// after = one space after pos
// PROBLEM
temp2 = curr.next;
Node after = curr.next;
while( after != null) {
after = after.next;
}
node.next = temp2;
curr.next = node;
break;
}
}
else {
curr = curr.next;
}
count--;
}
}
length++;
}
private void addFirst(T data) {
Node node = new Node(data);
if ( head == null ) {
head = node;
}
else {
Node temp = head;
head = node;
node.next = temp;
}
length++;
}
//TO-DO
public void remove( T data) {
if ( !search(data)) {
System.out.println("Linked list does not contain that element!");
return;
}
else if ( head.data == data) {
head = head.next;
}
else {
// If curr is the node to be deleted.
// link from previous node to curr, link from curr to next node
//Traverse through the linkedlist till it finds the node to be deleted and skip it
Node curr = head;
while ( curr != null & curr.next != null ) {
if ( curr.next.data == data) {
//Check if the node 2 next after curr is null
//if so, remove curr.next which contains the value that we want to delete
if ( curr.next.next != null) {
curr.next = curr.next.next;
}
//curr.next.next is null so just curr.next which contains the value we want to delete
else {
curr.next = null;
}
}
//Traverse the curr node
else {
curr = curr.next;
}
}
length--;
}
}
// Retrieves and removes the head of the priority queue
public T poll() {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return null;
}
else {
Node temp = null;
temp = head ;
head = head.next;
length--;
return temp.data;
}
}
// Retrieves the head of the priority queue
public T peek() {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return null;
}
else {
return head.data;
}
}
public void clear() {
Node curr = head;
while ( curr != null) {
curr = curr.next;
}
}
public int getSize() {
return length;
}
public boolean search(T data) {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return false;
}
else {
Node node = head;
while ( node != null ) {
if ( node.data == data) {
return true;
}
node = node.next;
}
return false;
}
}
public boolean isEmpty() {
if ( length == 0) {
return true;
}
return false;
}
#Override
public String toString() {
String str = "PQ: ";
Node node = head;
while ( node != null) {
str = str + node.data;
if ( node.next != null) {
str = str + ",";
}
node = node.next;
}
return str;
}
}
My main
public class priorityQueueImplementation {
public static void main(String[] args) {
PQLinkedList<Integer> test = new PQLinkedList<Integer>();
test.add(5);
test.add(10);
test.add(9);
test.add(11);
test.add(7);
test.add(2);
System.out.println( test.toString());
}
}
Since this is a singly linked list, we cannot add node to previous node. We can only add to subsequent node. During node insertion, we need to compare data with the list. One every node, there are 5 cases:
current is null, data become the new head
data is smaller than current, data become the new head
data is greater than current, data is smaller then next. Insert data between current and next
data is greater than current, next is null. Insert data after current
data is greater than current, data is greater then next. Wait for next iteration
public void addPQ(T data) {
Node node = new Node(data);
Node curr = head;
if (head == null) {
// current is null, data become the new head
addFirst(data);
} else {
while (curr != null) {
int cmpLeft = data.compareTo(curr.data);
if (cmpLeft < 0) {
// data is smaller than current, `data` become the new head
addFirst(data);
break;
} else {
// data is greater than current
if (curr.next == null) {
// next is null. Insert `data` after `current`
addAfter(curr, node);
break;
} else {
int cmpRight = data.compareTo(curr.next.data);
if (cmpRight < 0) {
// data is smaller then next. Insert data between current and next
addAfter(curr, node);
break;
}
}
// data is greater then next. Wait for next iteration
curr = curr.next;
}
}
}
}
private void addAfter(Node currNode, Node newNode) {
if (currNode == null) {
currNode = newNode;
} else {
Node tempTail = currNode.next;
currNode.next = newNode;
newNode.next = tempTail;
}
length++;
}
output
PQ: 2,5,7,9,10,11
Related
The code is working fine when I try to delete any element for some indices but for some others it is not working. For example, Whenever I try to delete by passing delete(1) it may work and if I try with delete(2) it may show NullPointerException. Here is the code :
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
n = n.next;
}
n.prev.next = n.next;
n.next.prev = n.prev;
}
}
So this is my code and You can see the delete method over there. I even run through debug mode, it is showing error at n.prev.next = n.next
Any kind of help is highly appreciated.
When I ran your code, the NullPointerException occurred on this line:
n.next.prev = n.prev;
and not on the line you said in your question.
The NullPointerException occurs when you delete the last Node in the list. This is because the value of next for the last Node in the list is null. So n.next is null and therefore n.next.prev throws NullPointerException.
You need to check whether n.next is null and only if it isn't you can execute the code: n.next.prev = n.prev.
Also, you need to check the value of parameter index in method delete(). One way would be to keep track of the number of elements in the list.
The below code incorporates the changes described. The parts I added are preceded by the comment Change here
public class DbLnkLst {
private static class Node {
int data;
Node next;
Node prev;
}
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
// Change here.
if (index < 0) {
throw new IllegalArgumentException("negative index: " + index);
}
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
// Change here.
if (n.next == null) {
throw new IllegalArgumentException("invalid index: " + index);
}
n = n.next;
}
n.prev.next = n.next;
// Change here.
if (n.next != null) {
n.next.prev = n.prev;
}
}
/**
* For testing the class.
*/
public static void main(String[] args) {
DbLnkLst list = new DbLnkLst();
list.insert(0);
list.insert(1);
list.insert(2);
System.out.println("List is:");
list.show();
list.delete(2);
System.out.println("After 'delete(2)', list is:");
list.show();
System.out.println("Try 'delete(2)' again.");
list.delete(2);
}
}
The output from running the above code is below:
List is:
0
1
2
After 'delete(2)', list is:
0
1
Try 'delete(2)' again.
Exception in thread "main" java.lang.IllegalArgumentException: invalid index: 2
at genrlprj/misctsts.DbLnkLst.delete(DbLnkLst.java:73)
at genrlprj/misctsts.DbLnkLst.main(DbLnkLst.java:100)
I'm trying to delete multiples nodes that meets a criteria from a linked list. The program is a bit complex so I'll get state the gist of it. The nodes in my linked list has the following characteristics (a name associated with a number):
Name Number
Dog 1
Cat 1
Rat 2
Donkey 3
Fish 1
I want to be able to delete the nodes with the number 1. My delete function:
public void Delete(Int N) {
Node current = Head;
Node previous = Head;
while (current.getNum() != N) {
if (current.getNextNode() == null) {
System.out.print("Not found");
} else {
previous = current;
current = current.getNextNode();
}
}
if (current == Head) {
Head = Head.getNextNode();
} else {
Node A = current.getNextNode();
previous.setNextNode(A);
}
}
This works but it only removes the first occurrence. I know it may be due to the lack of or appropriate loop structure but I've been working on this for hours and I'm getting confused along the way. I've tried doing a trace table manually but that's not working either.
How can the function be edited so it loops through the entire linked lists and removes the nodes that matches the criteria?
This should remove the matching Node instances from the linked list:
public void delete(int n) {
int count = 0;
Node prev = null, next;
for (Node current = head; current != null; current = next) {
next = current.getNextNode();
if (current.getNum() == n) {
count++;
if (prev != null) {
prev.setNextNode(next);
} else {
head = next;
}
} else {
prev = current;
}
}
System.out.print(count > 0 ? ("Number deleted: " + count) : "Not found");
}
Your loop while (current.getNum() != N) will end after the first occurrence of a node that has the number N. If you want to go through the entire list then the loop should look like
while (current != null) {
//do something with the list
current = current.getNextNode();
}
Specifically for this case you want to remove a node.
Node prev = null;
while (current != null) {
Node next = current.getNextNode()
if(current.getNum() == N){
//condition to remove current node has been found.
if(prev == null){
Head = next;
} else {
prev.setNextNode(next);
}
} else {
//only advance prev if we haven't deleted something
prev = current;
}
current = current.getNextNode();
}
If you want to delete a node in your linkedlist, you can use any of the following ways
a new linked list only with the nodes in which number is not equals to N
or modify the existing one.
I have used the first way, creating a new linked list with element in which number is not equals to N.
class Node {
public String name;
public int number;
public Node next;
}
public class LinkedListTest {
public static void main(String[] args) {
LinkedListTest obj = new LinkedListTest();
Node head = obj.createLinkList();
Node startPointer = head;
while (startPointer != null) {
System.out.println(startPointer.name + " " + startPointer.number);
startPointer = startPointer.next;
}
System.out.println("***********");
Node newNodeHead = obj.deleteNode(1, head);
startPointer = newNodeHead;
while (startPointer != null) {
System.out.println(startPointer.name + " " + startPointer.number);
startPointer = startPointer.next;
}
}
public Node deleteNode(int n, Node head) {
Node current = head;
Node newNodestartPointer = null;
Node newNodeCurrent = null;
while (current != null) {
if (!(current.number == n)) {
if (newNodestartPointer == null) {
newNodestartPointer = new Node();
newNodestartPointer.name = current.name;
newNodestartPointer.number = current.number;
newNodestartPointer.next = null;
newNodeCurrent = newNodestartPointer;
} else {
Node newNode = new Node();
newNode.name = current.name;
newNode.number = current.number;
newNodeCurrent.next = newNode;
newNodeCurrent = newNode;
}
}
current = current.next;
}
return newNodestartPointer;
}
public Node createLinkList() {
Node head = null;
Node newNode = new Node();
newNode.name = "Dog";
newNode.number = 1;
newNode.next = null;
head = newNode;
newNode = new Node();
newNode.name = "Cat";
newNode.number = 1;
newNode.next = null;
head.next = newNode;
Node prevNode = newNode;
newNode = new Node();
newNode.name = "Rat";
newNode.number = 2;
newNode.next = null;
prevNode.next = newNode;
prevNode = newNode;
newNode = new Node();
newNode.name = "Donkey";
newNode.number = 3;
newNode.next = null;
prevNode.next = newNode;
return head;
}
}
I have to implement a singly linked list for my project and I'm having trouble getting the remove method to work. I have searched on here for answers but I can't find any that incorporate the tail reference. My project needs to have a head and tail reference in the list and needs to be updated wherever necessary. This is my class and the remove method:
public class BasicLinkedList<T> implements Iterable<T> {
public int size;
protected class Node {
protected T data;
protected Node next;
protected Node(T data) {
this.data = data;
next = null;
}
}
protected Node head;
protected Node tail;
public BasicLinkedList() {
head = tail = null;
}
public BasicLinkedList<T> addToEnd(T data) {
Node n = new Node(data);
Node curr = head;
//Check to see if the list is empty
if (head == null) {
head = n;
tail = head;
} else {
while (curr.next != null) {
curr = curr.next;
}
curr.next = n;
tail = n;
}
size++;
return this;
}
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
head = n;
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}
public T getFirst() {
if (head == null) {
return null;
}
return head.data;
}
public T getLast() {
if(tail == null){
return null;
}
return tail.data;
}
public int getSize() {
return size;
}
public T retrieveFirstElement() {
// Check to see if the list is empty
if (head == null) {
return null;
}
Node firstElement = head;
Node curr = head.next;
head = curr;
size--;
return firstElement.data;
}
public T retrieveLastElement() {
Node curr = head;
Node prev = head;
// Check to see if the list is empty
if (head == null) {
return null;
} else {
// If there's only one element in the list
if (head.next == null) {
curr = head;
head = null;
} else {
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
tail = prev;
tail.next = null;
}
}
size--;
return curr.data;
}
public void remove(T targetData, Comparator<T> comparator) {
Node prev = null, curr = head;
while (curr != null) {
if (comparator.compare(curr.data, targetData) == 0) {
//Check to see if we need to remove the very first element
if (curr == head) {
head = head.next;
curr = head;
}
//Check to see if we need to remove the last element, in which case update the tail
else if(curr == tail){
curr = null;
tail = prev;
prev.next = null;
}
//If anywhere else in the list
else {
prev.next = curr.next;
curr = curr.next;
}
size--;
} else {
prev = curr;
curr = curr.next;
}
}
}
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
#Override
public boolean hasNext() {
return current != null;
}
#Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
#Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
}
}
I have went through many iterations of this method and each time I either lose the head reference, the tail reference or I don't remove the element and I am stumped trying to figure it out. For reference here is the test I'm running on it. I don't even fail the test, it just says failure trace.
public void testRemove(){
BasicLinkedList<String> basicList = new BasicLinkedList<String>();
basicList.addToEnd("Blue");
basicList.addToEnd("Red");
basicList.addToEnd("Magenta");
//Blue -> Red -> Magenta -> null
basicList.remove("Red", String.CASE_INSENSITIVE_ORDER);
//Blue -> Magenta -> null
assertTrue(basicList.getFirst().equals("Blue"));
//getLast() returns the tail node
assertTrue(basicList.getLast().equals("Magenta"));
}
EDIT: Forgot to mention that the remove method should be removing all instances of the target data from the list.
I see only 1 bug. If your list is initially empty the following method will cause a loop where you have one node whose next refers to itself:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
// The list was empty so this if is true
if(head == null){
head = n;
tail = n;
}
n.next = head;
// now head == n and n.next == head == n so you've got a circle
head = n;
size++;
return this;
}
You can fix this like so:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}
I have a project where I have to write a bunch of sort methods and measure the time complexity for each, and output the results to an output text file. the program runs but i get some null pointer exceptions in bubblesort method. here is my code and error, if you can tell me how to fix my sort methods, that would be awesome!
linked list class:
public class LinkedList {
protected static class Node {
Comparable item;
Node prev, next;
public Node(Comparable newItem, Node prev, Node next) {
this.item = newItem;
this.prev = prev;
this.next = next;
}
public Node (Comparable newItem) {
this(newItem, null, null);
}
public Node() {
this(null, null, null);
}
public String toString() {
return String.valueOf(item);
}
}
private Node head;
private int size;
public int dataCompares, dataAssigns;
public int loopCompares, loopAssigns;
public int other;
public LinkedList() {
head = new Node(null, null, null);
head.prev = head;
head.next = head;
size = 0;
}
public boolean add(Comparable newItem) {
Node newNode = new Node(newItem);
Node curr;
if(isEmpty()) {
head.next = newNode;
head.prev = newNode;
newNode.next = head;
newNode.prev = head;
} else {
newNode.next = head;
newNode.prev = head.prev;
head.prev.next = newNode;
head.prev = newNode;
}
size++;
return false;
}
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head;
while(curr!=null) {
if(curr.item.compareTo(item)==0) {
if(prev==null) {
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
public void removeAll() {
this.head.prev = null;
this.head.next = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean remove(Object item) {
return true;
}
public void insertSortNode() {
Node back = head;
if (size < 2)
return;
back = back.next; // SECOND entry in the list
while ( back != null ) { // I.e., end-of-list
Comparable value = back.item;
Node curr = head; // Start at the front
// Find insertion point for value;
while (curr != back && value.compareTo(curr.item) >= 0)
curr = curr.next;
// Propogate values upward, inserting the value from back
while (curr != back){
Comparable hold = curr.item;
curr.item = value;
value = hold;
curr = curr.next;
}
back.item = value; // Drop final value into place!
back = back.next; // Move sorted boundary up
}
} // end insertSort()
public void selSort() {
Node front = head;
// Nothing to do on an empty list
if ( front == null )
return;
while ( front.next != null ) { // skips a one-entry list
Node tiny = front;
Node curr = front.next;
Comparable temp = front.item; // start the swap
for ( ; curr != null ; curr = curr.next ) {
if ( tiny.item.compareTo(curr.item) > 0 )
tiny = curr;
}
front.item = tiny.item; // Finish the swap
tiny.item = temp;
front = front.next; // Advance to the next node
}
// The structure is unchanged, so the validity of tail is unchanged.
}
public void bubbleSort() {
Node Trav=head.next;
Node Trail=head.next;
Comparable temp;
if (Trav != null)
Trav = Trav.next;
while(Trav!=null) {
if (Trav.item.compareTo(Trail.item)<0) {
temp = Trail.item;
Trail.item=Trav.item;
Trav.item = temp;
}
Trail=Trav;
Trav=Trav.next;
}
}
public void insertSortArray() {
Node insert1, cur, tmp1;
Comparable temp;
for(insert1 = this.head.next.next; insert1!=this.head; insert1 = insert1.next) {
//++loopcompares; ++loopassigns;
for (cur = head.next; cur!=insert1; cur=cur.next) {
//++loopCompares; ++loopassigns;
//++datacompares;
if(insert1.item.compareTo(cur.item)<0) {
temp=insert1.item;
//++dataassign
tmp1=insert1;
//++other
while(tmp1!=cur.prev) {
//++loopcomares
tmp1.item=tmp1.prev.item;
tmp1=tmp1.prev;
//++dataassign+=2
}
//++loopcompares
cur.item = temp;
//++dataassign;
break;
}
}
//++loopcompares; ++loopassigns;
}
//++loopcompares; ++loopassigns
}
public void disp6sortsFile(boolean disp, String fileName, String header, String data) {
FileWriter fw = null;
PrintWriter pw = null;
try {
File file = new File(fileName);
fw = new FileWriter(file, true);
pw = new PrintWriter(fw, true);
} catch (IOException e) {
System.err.println("File open failed for " +fileName+ "\n" + e);
System.exit(-1);
}
if (disp) {
pw.print(header + "\n");
}
pw.print(data + "\n");
pw.close();
}
}
here is my error:
Exception in thread "main" java.lang.NullPointerException
at LinkedList.bubbleSort(LinkedList.java:149)
at LinkListTester.main(LinkListTester.java:51)
the linkedlisttester error is simply list1.bubbleSort(); so bubble sort is the problem.
Change:
public String toString() {
return this.item.toString();
}
to:
public String toString() {
return String.valueOf(item); // Handle null too.
}
For add return true. Might check that item is not null if so desired.
remove is written for a single linked list.
In remove the head has a null item, which might have caused the error. Also as we have a circular list with a dummy node for head, the termination should not test for null but head. Otherwise a not present item will loop infinitely.
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head.next; // !
while(curr!=head) { // !
if(curr.item.compareTo(item)==0) {
if(prev==null) { // ! WRONG, but I will not correct home work ;)
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
swap is written for a single linked list.
And here I stopped reading, as I've come to the usages.
Second Edit:
All algorithmic functions, i.e. bubbleSort, have the following control flow:
while(Trav!=null) { ... Trav = Trav.next; }
But the data structure is defined cyclic, so eventually you arrive back at head and there the item is null.
The solution is to have for the first Node a prev null, and for the last Node a next null.
To make this clear, readable, you could substitute the Node head with:
Node first;
Node last;
Data structures class, implementing a singly linked-list with head, tail and current nodes. Having trouble with a method, could use a nudge in the right direction.
From the assignment, write the method:
add( item ) : adds the item (String) after the current node in the list and sets the current pointer to refer to the new node.
My attempt:
public void add(String item)
{
if(curr != null)
{
Node newNode = new Node(item, curr.next);
curr.next = newNode;
curr = newNode;
}
else
{
head = tail = new Node(item, null);
curr = head;
}
}
My add method only seems to work when I'm adding items to the middle of the list, not on either end. If I use it to add a few items and then print the list, only the first one I added will be on the list, while my prepend and append methods have tested just fine.
Is there any glaring issue with my code? I feel like I'm missing something obvious.
All:
public class LinkedList {
Node head = null; /* Head of the list */
Node tail = null; /* Tail of the list */
Node curr = null; /* Current node in the list */
public void prepend(String item) {
if (head == null) {
head = tail = new Node(item, null);
curr = head;
} else {
head = new Node(item, head);
curr = head;
}
}
public void append(String item) {
if (head == null) {
head = tail = new Node(item, null);
curr = tail;
} else {
tail.next = new Node(item, null);
tail = tail.next;
curr = tail;
}
}
public void add(String item) {
if (curr != null) {
Node newNode = new Node(item, curr.next);
curr.next = newNode;
curr = newNode;
} else {
head = tail = new Node(item, null);
curr = head;
}
}
public void delete() {
if (curr.next == null) {
Node temp = head;
while (temp.next != curr) {
System.out.println(temp.item);
temp = temp.next;
}
temp.next = null;
curr = head;
}
}
public void find(String item) {
Node temp = new Node(curr.item, curr.next);
if (item.equals(temp.item))
curr = temp;
else {
temp = temp.next;
while (temp.next != null && temp != curr) {
if (item.equals(temp.item))
curr = temp;
}
}
}
public String get() {
if (curr != null)
return curr.item;
else
return "";
}
public boolean next() {
if (curr != tail) {
curr = curr.next;
return true;
} else
return false;
}
public void start() {
curr = head;
}
public void end() {
curr = tail;
}
public boolean empty() {
if (head == null)
return true;
else
return false;
}
}
Node class:
class Node {
Node next;
String item;
Node(String item, Node next) {
this.next = next;
this.item = item;
}
}
There is indeed a problem in add: it doesn't update tail when nodes already exist. Consider this sequence of actions:
LinkedList list = new LinkedList();
list.add("one");
list.add("two");
list.append("three");
If you were to then print it using this:
public void print() {
Node curr = this.head;
while(curr != null) {
System.out.println(curr.item);
curr = curr.next;
}
}
Like this:
list.print();
You'd get the following output:
one
three
This happens because tail -- which append relies on -- continues to point to the first Node after the second add operation is performed.
I don't see any problems here, so I would guess the issue is elsewhere.
Okay, the only issue I see there is in delete:
public void delete()
{
Node temp = head;
while(temp != null && temp.next != curr) {
System.out.println(temp.item);
temp=temp.next;
}
if (temp != null && temp.next != null) {
temp.next = temp.next.next;
}
curr = head;
}
I think I have found your problem.
If you use append() you add it directly after the tail. But when you have added previous nodes after the tail you don't set your tail to the new node. This means that once you call append() twice you loose all the nodes that you have added after the first append().
Brief example:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("First add");
list.append("First Append");
list.add("Second add");
list.prepend("First prepend");
list.add("Third add");
list.prepend("Second prepend");
list.add("fourth add");
list.append("Second Append");
list.add("Fifth add");
list.add("Sixth add");
list.start();
do {
System.out.println(list.get().toString());
} while (list.next());
}
Output:
Second prepend
fourth add
First prepend
Third add
First add
First Append
Second Append
Conclusion: "Second Add" is lost, as well as "Fifth add" and "Sixth add" because your next() method stops as soon as it reaches the tail. You need to always update the tail if you add a new node in the end.
Hope this helps.
Cheers, Chnoch
I think the problem is
if (curr != null) {
Node newNode = new Node(item, curr.next); //<-- here (curr.next)
//and
Node(String item, Node next) {
this.next = next; //<-- here
Try (Edited):
Node newNode = new Node(item, curr); // pass curr to the constructor of Node
curr = newNode;