Java linked list used in Stack - java

To improve a little bit myself in data structures i tried to design my own Stack. To do so I decided to use a linked list to let me use undefined length stacks (and because I come from C programming). My code is:
public class Main {
public static void main(String[] args) {
Stack stk = new Stack();
obj buf_el;
Scanner s=new Scanner(System.in);
boolean stop=false;
do{
String buffer= s.next();
System.out.println("Created first buff");
if(buffer.equals("exit")) stop=true;
if(buffer.equals("pop")){
buf_el = stk.pop();
System.out.println("Element Popped from stack:\t\t[#]\t-->\t"+buf_el.field());
}
else if(buffer.equals("push")){
obj pushed = new obj(s.next());
stk.push(pushed);
System.out.println("Element pushed in the stack:\t\t[#]\t<--\t"+pushed.field());
}
else if(buffer.equals("stats")) stk.stats();
else if(buffer.equals("all")) stk.traverse();
}
while(stop==false);
}
}
class obj{
private String field = new String();
private obj next = null;
private obj back = null;
obj (String field){
this.field=field;
}
public obj() {
}
void concat(obj next){
this.next=next;
this.next.back=this;
}
void del(){
this.next=null;
this.back.concat(null);
}
obj next(){
return this.next;
}
obj back(){
return this.back;
}
String field(){
return this.field;
}
}
class Stack{
private obj head = null;
private obj tail = null;
private int pops=0;
private int pushes=0;
void push(obj el){
pushes++;
if(this.head==null | this.tail==null){
this.head = el;
this.tail = el;
}
else{
head.concat(el);
}
}
obj pop(){
if(head==null & tail==null) System.out.println("The stack is empty, Operation failed.");
else{
pops++;
if(this.head==this.tail){
System.out.println("This is the last element; the stack is empty now");
obj ret=new obj(this.head.field());
this.head=null;
this.tail=null;
return ret;
}
else{
obj ret=new obj(this.head.field());
this.head=this.head.back();
return ret;
}
}
return null;
}
void stats(){
System.out.println("Number of pops\t||\t"+pops);
System.out.println("Number of pushes\t||\t"+pushes);
System.out.println("Length of the stack\t||\t"+(pushes-pops));
}
void traverse(){
if(head==null & tail==null) System.out.println("The stack is empty, Operation failed");
obj cursor=null;
System.out.println(" TAIL");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\tV");
do {
cursor=tail;
System.out.println(cursor.field());
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\tV");
cursor=cursor.next();
}
while(cursor!=null);
System.out.println(" HEAD");
}
}
GitHub
But it has a big problem: when i push a new element it is overwritten on the previous element. Where is the error? Probably I misunderstood something related to the "by reference" practices in Java. Moreover, what methods would you use to make such a programm?
P.S. I know that there is a stack library, but I believe it would be good to code these things to improve my knowledge of the language.

I made two changes to make ik work:
first in a push you have to make th new element head
void push(obj el) {
pushes++;
if (this.head == null | this.tail == null) {
this.head = el;
this.tail = el;
} else {
el.concat(head);
head = el;
}
}
second in o pop you must make the next element head
obj pop() {
if (head == null & tail == null)
System.out.println("The stack is empty, Operation failed.");
else {
pops++;
if (this.head == this.tail) {
System.out.println("This is the last element; the stack is empty now");
obj ret = new obj(this.head.field());
this.head = null;
this.tail = null;
return ret;
} else {
obj ret = new obj(this.head.field());
this.head = this.head.next();
return ret;
}
}
return null;
}
EDIT
didnt't check traverse, had to change it too:
void traverse() {
if (head == null & tail == null)
System.out.println("The stack is empty, Operation failed");
obj cursor = null;
System.out.println(" TAIL");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\tV");
cursor = tail;
while (cursor != null) {
System.out.println(cursor.field());
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\t|");
System.out.println("\tV");
cursor = cursor.back();
}
System.out.println(" HEAD");
}

You should try to overwrite the function equalsTo in your Obj class;
It should look like that :
#Override
public boolean equals(obj o){
if (o.field.equalsTo(this.field) {
return true;
}
}
like that, this should work
if(this.head==null | this.tail==null){
this.head = el;
this.tail = el;
}
else{
head.concat(el);
}

I have seen to issue in you code.First if you want to add to end then concat using tail and move the tail to current node.if you push t1 head and tail both point to same node after that t2 add and head will point to t1 and tail will t2.That part missing in your code.
tail.concat(el);
tail=tail.next();
Second in traverse process loop initialize once out side loop
cursor=head;

Related

I have a problem in the reference of my 'head' node in my own LinkedList Class

I had written my own Linked Class Codes with Node first and last, since there exists a Node last, I encountered problems regarding reference and pointer manipulations when I tried to manually created the LinkedList in the main method and test it.
I am quite familiar with the recursion implemented in the "addFirst" "addLast" and "remove" methods, but now somehow the reference to the Node first becomes null after addFirst Method.
public class LinkedList<T> {
Node first,last,temp;
public class Node{
T value;
Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public String toString(){
if(next == null){
return value.toString();
}
else{
return value.toString() + " " + next.toString();
}
}
public T getLL(int index){
if(index == 0){
return value;
}
if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
return next.getLL(index-1);
}
public T removeLL(int x){
if(x == 1){
T value = next.value;
next = next.next;
return value;
}
else if(next == null){
throw new
IndexOutOfBoundsException("have reached the end of the list, none found");
}
else{
return next.removeLL(x-1);
}
}
}
public LinkedList(T value) {
temp = new Node(value,null);
first = new Node(value,null);
last = temp;
}
public static void main(String[] args) {
/**
* [120,110,100,90,80];
*/
LinkedList L = new LinkedList(100);
L.addFirst(110);
L.addFirst(120);
L.addLast(90);
L.addLast(80);
System.out.println(L.size());
System.out.println(L.remove(0));
System.out.println(L.last.toString());
//return null which causes the remove method not to work.
System.out.println(L.first);
}
public void addFirst(T value){
first = new Node(value,first);
}
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
last.next = new Node(value,null);
last = new Node(value,null);
}
public T get(int index){
if(first == null){
throw new IndexOutOfBoundsException("empty list");
}
return first.getLL(index);
}
public int size(){
int c = 0;
while(first != null){
first = first.next;
c++;
}
return c;
}
public T remove(int x){
if(first == null){
throw new IndexOutOfBoundsException("Tried to remove from empty list");
}
if (x == 0) {
T value = first.value;
first = first.next;
return value;
}
return first.removeLL(x);
}
}
I expected that the Node first pointed to the first element of the LinkedList instead of pointing to null. Meanwhile, this won't affect the pointer of Node last.
Looks like the problem inside the AddLast function. You braking the list.
Shouldn't it be like this?
public void addLast(T value){
Node p = first;
if( p == null){
first = last = new Node(value,null);
}
while(p.next!= null){
p = p.next;
}
p.next = new Node(value,null);
last = p.next;
//last = new Node(value,null);
}
Update Regarding your comment and updated answer.
Your size function is wrong:
public int size(){
int c = 0;
while(first != null){
first = first.next; // <-- now first point to the last and length is 1
c++;
}
return c;
}
When you remove the first element first is null. You have to create temporary variable to traverse your list. To check this comment the line where you calculate size.
Your are actually not quite right last.next = new Node(value,null); point to the new node. But instead of connecting again last = last.next your new node is gone because you create your new node for the last but last.next pointed to new node and hence last is not last anymore. (I think your understood what I meant)

stack and queues using doubly linked list in java

I have some problems that code. I read file in code and build one stack and one queues structure. But the code wasn't run correctly.
This is Node class
I used Double LinkedList
public class Node
{
String data;
Node next;
Node prev;
public Node(String data,Node next, Node prev){
this.next=next;
this.data=data;
this.prev=prev;
}
public Node(){
}
public String getData(){
return data;
}
public void setData(String data){
this.data=data;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next=next;
}
public Node getPrev(){
return prev;
}
public void setPrev(Node prev){
this.prev=prev;
}
}
** this is stack class. **
public class Stack {
Node head = null;
Node tail = null;
int size=0;
public int getSize() {
return size;
}
public boolean isEmpty()
{
return head == null;
}
public void Push(String data) {
tail = head;
head = new Node(data,null,null);
head.data=data;
head.next= tail;
head.prev = null;
if(tail != null) {
tail.prev=head;
}
size++;
}
public void Pop() {
if (!isEmpty()) {
head = head.next; // delete first node
size--;
} else {
System.out.println("İs Empty");
}
}
public void Top() {
Node tmp = head;
while (tmp != null) {
System.out.println(tmp.getData());
tmp = tmp.getNext();
}
}
}
This is Queues Class
public class Oueues {
Node head ;
Node tail;
int size=0;
public Oueues(){
this.head=null;
this.tail=null;
}
public boolean isEmpty()
{
return head == tail;
}
public int getSize()
{
return size;
}
public void insert(String data){
Node tmp = new Node(data,null,null);
tmp.data=data;
tmp.next=null;
if(head==null){
head=tail=tmp;
head.prev=null;
}
else{
tail.next=tmp;
tmp.prev=tail;
tail=tmp;
}
}
public String remove(){
if(head.next==tail)
return null;// list empty
Node tmp=head.next;
head.next=tmp.next;
tmp.next.prev=head;
list();
return tmp.data;
}
public void list(){
System.out.println("Queues");
if(size==0){
System.out.println("İs Empty");
}
Node tmp=head;
while(tmp !=tail.getNext()){
System.out.println(tmp.getVeri()+" ");
tmp= tmp.getNext();
}
System.out.println();
}
}
This is Queues Class
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OGrenci {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
Stack y = new Stack();
Oueues k = new Oueues();
FileWriter fwy;
FileWriter fwk;
File stack = new File("stack.txt");
if (!stack.exists()) {
stack.createNewFile();
} else {
System.out.println("already exists ");
}
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(stack));
String line = reader.readLine();
while (line != null) {
y.Push(line = reader.readLine());
System.out.println(line);
}
File queue = new File("queue.txt");
if (!queue.exists()) {
queue.createNewFile();
} else {
System.out.println("already exists ");
}
BufferedReader read = null;
read = new BufferedReader(new FileReader(queue));
String lines = read.readLine();
while (lines != null) {
lines = read.readLine();
k.insert(lines);
System.out.println(lines);
}
int choice;
System.out.println("1. Stack out- queue add");
System.out.println("2. Stack add- queue out");
System.out.println("3. Stack and queue ");
System.out.println("4. File writer");
choice = s.nextInt();
switch (choice) {
case 1:
k.insert(s.next());
k.list();
y.pop();
break;
case 2:
y.Push(s.next());
y.Top();
k.remove();
break;
case 3:
y.Top();
k.list();
break;
case 4:
fwy = new FileWriter(stack);
Node no = y.head;
while (no.next != null) {
fwy.write("\n" + no.data);
no = no.next;
}
fwy.flush();
fwy.close();
fwk = new FileWriter(queue);
Node noo = k.head;
while (noo.next != null) {
fwk.write("\n" + noo.data);
noo = noo.next;
}
fwk.flush();
fwk.close();
break;
}
}
Ok, so you have a couple of problems. I'm going to point out a few and let you work to fix the rest because this looks like an assignment and I don't want to do your homework for you :).
First, when you read from the file be careful not to ignore the first element:
String line = reader.readLine();
while (line != null)
{
System.out.println("Read from stack: " + line);
// we already read one element
y.Push(line);
line = reader.readLine();
}
Notice that unlike your solution I first do the push y.Push(line) so that we don't forget to add whatever is already read into line. Same goes for the queue file:
String lines = read.readLine();
while (lines != null)
{
System.out.println("Read from queue: " + lines);
// we already read one line
k.insert(lines);
lines = read.readLine();
}
Just add it if it's not null and then read the next line. You were always missing on the first element from the file.
Another problem is the Queues class (which by the way is misspelled you should replace O with Q). This one is not working properly because you forgot to increment and decrement the size when you insert or remove.
public void insert(String data){
Node tmp = new Node(data,null,null);
tmp.data=data;
tmp.next=null;
if(head==null){
head=tail=tmp;
head.prev=null;
}
else{
tail.next=tmp;
tmp.prev=tail;
tail=tmp;
}
size++;
}
Notice that at the end of insert I'm increasing the size so that the list method doesn't throw a NullPointerException every time we call it. Same goes for the remove method:
public String remove(){
if(head == null)
return null;// list empty
Node tmp=head.next;
head.next=tmp.next;
tmp.next.prev=head;
size--;
list();
return tmp.data;
}
Please also notice that your check before (if(head.next==tail)) was also throwing NullPointerException because at the beginning the head is always null so you cannot access the next member.
Finally I've made a small improvement to the list method as well so that we return earlier:
public void list(){
System.out.println("Queues");
if(size==0){
System.out.println("İs Empty");
return;
}
Node tmp=head;
while(tmp != tail.getNext()){
System.out.println(tmp.getData() + " ");
tmp= tmp.getNext();
}
System.out.println();
}
Notice the return if the Queue is empty, otherwise we will attempt to do tail.getNext() which will always throw a NullPointerException.
Some important thoughts about the code in general
Please avoid weird naming. Why Queues? There is just one so it should be Queue.
Please avoid weird variable names. Your code is not just for you, chances are someone else might need to read and it gets hard to know who it is s, y, k, fwy and fwk. Why not naming them like this:
Scanner scanner = new Scanner(System.in);
Stack stack = new Stack();
Queues queue = new Queues();
FileWriter stackFileWriter;
FileWriter queueFileWriter;
And the same goes for methods . Why Push, Pop and Top are the only methods that start with upper-case letter ? If you don't agree with the standard Java naming convention that is fine but at least be consistent :).
Try the suggested improvements and see how your program it's working. I'm almost sure there are more problems with it. If you can't figure them out yourself leave a comment and I will help you. Good luck!

Delete a node from a linkedlist

class StackNode{
int data;
StackNode next;
public StackNode(int data, StackNode next){
this.data = data;
this.next = next;
}
}
public class StackWithLinkedList {
StackNode root = null;
public void push(int data){
if(root == null)
root = new StackNode(data, null);
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
temp.next = new StackNode(data, null);
}
}
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
StackNode temp = root;
while(temp.next != null)
temp = temp.next;
int data = temp.data;
temp = null;
return data;
}
}
public void print(){
StackNode temp = root;
while(temp!= null){
System.out.print(temp.data +" ");
temp = temp.next;
}
System.out.print("\n");
}
public static void main(String[] args) {
StackWithLinkedList stack = new StackWithLinkedList();
for(int i = 1; i<=15; i++){
Random randomGen = new Random();
stack.push(randomGen.nextInt(i));
}
stack.print();
System.out.print("\n");
try {
System.out.println("Deleted: "+stack.pop());
System.out.println("Deleted: "+stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
stack.print();
}
}
I am trying to implement Stack with Linkedlist. In pop function i am traversing till the last node and making it null. When i print the list. it remain unchanged. Does assigning root to temp and traversing with it cause any problem?
You can avoid this all together by simplifying your implementation. It's just a stack so it's LIFO. All you need to do is make the last element push-ed the root. When pop-ing return the data in root and set root to the next in line.
The way you're doing it increases the typical complexity of O(1) to O(N) for the push and pop operations.
Something like:
public void push(int data) {
root = new StackNode(data, root);
}
public int pop() throws Exception {
if (root == null)
throw new Exception("No Elements in Stack");
else {
int data = root.data;
root = root.next;
return data;
}
}
As mentioned in other answer by #ChiefTwoPencils, that must be the preferred way of implementing this. However, to correct your logic of pop operation you shall keep track of second last item and once you get that you can return data value of next node and set the next link to null.
Here is changed logic from your code of pop method
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
int data = -1;
if(root.next==null) {
data = root.data;
root = null;
return data;
}
StackNode temp = root;
while(temp.next.next != null)
temp = temp.next;
data = temp.next.data;
temp.next = null;
return data;
}
}
Hope it helps.
public int pop() throws Exception{
if(root == null)
throw new Exception("No Elements in Stack");
else {
StackNode temp = root;
StackNode prev;
while(temp.next != null){
prev = temp;
temp = temp.next;
}
int data = temp.data;
prev.next = null;
return data;
}
}

Can a method return another method with same return type?

Here are my code blocks in my Doubly-Linked List (circular) implementation.
Can it return a method, like the return statement for addBefore method?
public boolean addAfter(int value, int target) {
Node targetNode = findExact(target);
Node temp = new Node(value);
if(targetNode == null) {
return false;
} else if((targetNode.next == null)) { //prevNode is head, when list.size = 1
temp.next = head;
temp.prev = targetNode;
targetNode.next = temp;
head.prev = temp;
size++;
return true;
} else if(targetNode.next == head) { //prevNode is tail,
temp.next = targetNode.next;
temp.prev = targetNode;
targetNode.next = temp;
head.prev = temp;
size++;
return true;
} else { //prevNode is a node inbetween two nodes
temp.next = targetNode.next;
temp.prev = targetNode;
targetNode.next = temp;
temp.next.prev = temp;
size++;
}
return true;
}
public boolean addBefore(int value, int target) {
Node targetNode = findPrev(target);
return addAfter(value, targetNode.data);
}
I think you want to state returning a value from method in case of addBefore method where you want to leverage addAfter. That bit is valid and you should look at the semantic of your underlying method addAfter and possibly findExact as to what they are returning that is leading to NPE.
It is also possible to return a method, don't think you need it here nonetheless this assumes there is a method called myMethod which takes an array of integer, the syntax will look something as below:
Method myMethod;
try {
myMethod = TestApp.class.getDeclaredMethod("myMethod", int[].class);
myMethod.invoke(null, ar);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this helps

null pointer exception in my bubblesort, and other sort methods

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;

Categories

Resources