stack and queues using doubly linked list in java - 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!

Related

InsertionSort on Linked List , with Data from text file. Java

I'm doing insertion sort with my Linked List, and I have faced an issue.
My Data file:
Myjob 66
Junk 17
Fun 25
Vital 99
Important 96
MoreFun 28
Work 69
Assignment 44
Here is my code for Insertion Sort
public Node insertSort(Node node){
Node sortedNode = null;
while(node != null){
Node current = node;
node = node.next;
Node x;
Node previous = null;
for(x = sortedNode; x != null; x = x.next){
if(current.getData().getNum() > x.getData().getNum()){
break;
}
previous = x;
}
if(previous == null){
current.next = sortedNode;
sortedNode = current;
}
else{
current.next = previous.next;
previous.next = current;
}
}
sortedNode=head;
return sortedNode; }
My currently output:
Name = Myjob Priority=66
Name = Assignment Priority=44
Name = MoreFun Priority=28
Name = Fun Priority=25
Name = Junk Priority=17
null
they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help. I'm very new in Java. Thank you so much.
My Data Class
public class Data {
private String name;
private int num;
public Data(){
}
public Data(String name,int num){
this.name=name;
this.num=num;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getNum(){
return num;
}
public void setNume(int num){
this.num=num;
}
public String toString()
{
return "Name = " + name + " Priority=" + num ;
}
}
Here is my LinkedList Class:
public class LinkedList {
Node head;
Node prev;
Node cur;
public LinkedList(){
}
public LinkedList(Node head){
head = null;
}
//getter to get head
public Node gethead(){
return head;
}
public void printLinkedList(){
System.out.println(head);
}
public void initializeLL(){
Node currentNode = head;
try
{
File file = new File("Asg2Data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNext())
{
Data d = new Data(sc.next(), sc.nextInt());
Node n = new Node(d);
if(currentNode == null){
currentNode = n;
head = n;
}else{
currentNode.setNext(n);
currentNode = n;
}
}
sc.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException{
LinkedList l1 = new LinkedList();
l1.initializeLL();
l1.insertSort(l1.head);
l1.printLinkedList();
System.out.println("************");
}
}
Here is my Node Class:
public class Node{
Data dt;
Node next;
public Node(){
}
public Node(Data dt){
this.dt=dt;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next=next;
}
public Data getData(){
return dt;
}
public void setData(Data dt){
this.dt=dt;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(dt).append(System.getProperty("line.separator"));
sb.append(next).append(System.getProperty("line.separator"));
return sb.toString();
}
}
The insertionSort method is inside the LinkedList Class.
There are a couple of things going on here. Firstly you have some bugs in your code like returning head which has not been updated. This can easily explain the behaviour you are seeing, by starting the iteration halfway through the list.
More importantly this does not seem to be an implementation of insertion sort to me. Insertion sort is done by inserting into an already sorted list at the correct point. So would look like:
sortedList Sort(unsortedlist):
sortedList = []
foreach item in unsortedlist:
sortedList.InsertAtTheRighPlace(item)
return sortedList
Are you sure your code here is correct?
I trace your code and I find that for loop is not run anyway because x is always null in each run of insertSort() function.
How you call insertSort() function to sort data?
EDIT:
Ok. I review your code. I found that your sort is correct but after sorting function head of LinkList is not update. So your code prints sorted list from old head.
You should update head of linkedlist after sort function.
Ok So the code fragment below Here is my code for Insertion Sort is making some serious workarounds that I guess even you won't be able to properly imagine :).
Try breaking your problem into simpler steps, How would you have gone to implement a LinkedList where you could just add an Integer(Anything really, just the OOP complexity varies) in Ascending or Descending form. The following code that I just tested would help you atleast see how you should have implemented a LinkedList that grows via InsertionSort algo , note that this is dealing the ascending order case
public class LinkedList
{
public Node first , last;
public class Node
{
public int data;
public Node next;
public Node( int data )
{
this.data = data;
}
}
public void addInsertSort( int num )
{
if( isEmpty() )
{
first = new Node( num );
last = first;
}
else
{
Node newNode = new Node( num );
Node curNode = first , preNode = null;
while( curNode != null && newNode.data > curNode.data )
{
preNode = curNode;
curNode = curNode.next;
}
if( curNode == first )
{
newNode.next = first;
first = newNode;
}
else
{
if( curNode != null && preNode != null ) //middle of list
{
newNode.next = curNode;
preNode.next = newNode;
}
else if( curNode == null ) // end of list
{
preNode.next = newNode;
last = newNode;
}
}
}
}
public boolean isEmpty()
{
return first == null;
}
public String toString()
{
String str = "[";
for( Node curNode = first; curNode != null; curNode = curNode.next )
{
str += curNode.data + " ";
}
return str + "]";
}
public static void main( String[] args )
{
LinkedList list = new LinkedList();
list.addInsertSort( 4 );
list.addInsertSort( 5 );
list.addInsertSort( 1 );
list.addInsertSort( 6 );
list.addInsertSort( 10 );
list.addInsertSort( 0 );
System.out.println( list );
}
}
Im sorry, the code editor here is REALLY KILLING ME, please don't mind the frequent re-edits
Now going on with how you would integrate this idea in your methods, you can fix things like this, and make sure it looks exactly this way
// You really dont need more variables in your LinkedList class
// Both of these are enough, forget currentNode reference
public Node head , last;
public void initializeLL(){
try
{
File file = new File("Asg2Data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNext())
{
Data d = new Data(sc.next(), sc.nextInt());
Node n = new Node(d);
addInsertSort( n );
}
sc.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public Node addInsertSort( Node newNode )
{
if( isEmpty() )
{
head = newNode;
last = head;
}
else
{
Node curNode = head , preNode = null;
// This is How InsertionSort would have gone to search the list
while( curNode != null && newNode.getData().getNum() > curNode.getData().getNum() )
{
preNode = curNode;
curNode = curNode.next;
}
//Thats the happy ending of the insertionSort algo
//Now we need to link newNode with OUR DYNAMICALLY GROWING LIST
//When the insertion Algo stopped, It told us where the newNode
//shall be placed in comparison to the current state of list
// Is this supposed to be the head node now??
if( curNode == head )
{
newNode.next = head;
head = newNode;
}
else // maybe we landed BETWEEN the list or at the END OF LIST??
{
if( curNode != null && preNode != null ) //BETWEEN THE list
{
newNode.next = curNode;
preNode.next = newNode;
}
else if( curNode == null ) // end of list
{
preNode.next = newNode;
last = newNode;
}
}
}
return newNode;
}
public boolean isEmpty()
{
return head == null;
}
Let me know if something still goes wrong, I will explain more deeply

Java linked list used in Stack

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;

Implement a Stack with a circular singly linked list

I'm trying to implement the a Stack in Java with a circular singly linked list as the underlying data structure. I placed the insert function for a circular linked list in replacement of the push function for the stack and so on. I don't have any errors but I'm having troubles displaying the stack. If anyone could point me in the right direction of how to display the stack or what's going wrong I'd really appreciate it!
Here is my stack class:
public class Stack {
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
private Node current = null; // reference to current node
private int count = 0; // # of nodes on list
private long iData;
public Stack(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
public void push(long j) // put item on top of stack
{
Node n = new Node(j);
if(isEmpty()){
current = n;
}
n.next = current;
current = n;
count++;
}
//--------------------------------------------------------------
public Node pop() // take item from top of stack
{
if(isEmpty()) {
return null;
}
else if(count == 1){
current.next = null;
current = null;
count--;
return null;
}else{
Node temp = current;
current = current.next;
temp.next = null;
temp = null;
count--;
}
return current;
}
//--------------------------------------------------------------
public Node peek(long key) // peek at top of stack
{
Node head = current;
while(head.iData != key){
head = head.next;
}
return head;
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (count == 0);
}
//--------------------------------------------------------------
public boolean isFull() // true if stack is full
{
return (count == maxSize-1);
}
//--------------------------------------------------------------
Here is my constructor class
public class Node{
public long iData; // data item (key)
public Node next; // next node in the list
public Node(long id){ // constructor
iData = id; // next automatically nulls
}
public void displayNode(){
System.out.print(iData + " ");
}
public static void main(String[] args) {
Stack newlist = new Stack(3);
newlist.push(1);
newlist.push(2);
newlist.push(3);
newlist.push(4);
newlist.pop();
newlist.pop();
newlist.push(4);
newlist.pop();
newlist.peek(1);
newlist.push(5);
while( !newlist.isEmpty() ) // until it’s empty,
{ // delete item from stack
Node value = newlist.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
}
//newlist.displayList();
}
First, in your main function you are printing value using System.out.print function. This displays the object's class name representation, then "#" followed by its hashcode.
Replace following lines
System.out.print(value); // display it
System.out.print(" ");
with
value.displayNode();
Second, in pop method, you are returning null when count is 1. It should return the last element which is present in the list. Also, in last else if clause, you should return temp. Replace your code with this.
public Node pop() // take item from top of stack
{
if (isEmpty()) {
return null;
}
Node temp = current;
if (count == 1) {
current = null;
} else {
current = current.next;
}
count--;
temp.next = null;
return temp;
}
A few notes on your implementation:
1) stackArray member seems to be a leftover from another array based stack implementation.
2) is max size really a requirement? if so, you don't enforce the stack size limitation in push(..)
3) Your push(..) method doesn't keep the list circular. You should close the loop back to the new node.
4) Adding a dummy node allows you to keep the linked list circular, regardless of the stack size. This can make your push(..) method simpler (as well as any iteration for printing purposes for example)
5) The peek() method contract is unclear. Usually you want the peek method to return the value in the top of the stack, without removing it. Also, why do you return type Node? This class should be hidden from the caller - it's an internal implementation detail, not something you want to expose in your API.
Following is an alternative implementation, that also supports toString():
public class Stack {
private Node EOS;
private int count = 0;
public Stack() {
EOS = new Node(0);
EOS.next = EOS;
}
public void push(long j) {
Node newNode = new Node(j);
Node tmp = EOS.next;
EOS.next = newNode;
newNode.next = tmp;
count++;
}
public Long pop() {
if (isEmpty()) {
return null;
} else {
count--;
Node node = EOS.next;
EOS.next = node.next;
return node.iData;
}
}
public Long peek() {
if (isEmpty()) {
return null;
} else {
Node node = EOS.next;
return node.iData;
}
}
public boolean isEmpty() {
return (count == 0);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node p = EOS.next;
while (p != EOS) {
sb.append(p).append("\n");
p = p.next;
}
return sb.toString();
}
private static class Node {
public long iData;
public Node next;
public Node(long id) {
iData = id;
}
#Override
public String toString() {
return "<" + iData + ">";
}
}
}

Exception in thread "main" java.util.NoSuchElementException: No line found - Using scanner input [duplicate]

This question already has answers here:
Java Scanner.nextLine() not waiting for input
(2 answers)
java.util.NoSuchElementException: No line found
(7 answers)
Closed 9 years ago.
I am trying to delete a specific node from a linked list. I am trying to call my method removeNode, but it is giving me this error when I call it to get the user input. Any advice on how to fix this would be greatly appreciated!
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at LinkedList.removeNode(LinkedList.java:123)
at fileIn.<init>(fileIn.java:22)
at fileIn.main(fileIn.java:13)
LinkedList class:
import java.util.Scanner;
public class LinkedList {
public LinkedListNode front;
public LinkedList() {
this.front = null;
}
public void insertBack(String data)
{
if(front == null){
front = new LinkedListNode(data);
}
else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = front;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}//end insertBack
public void addAfter(LinkedListNode spot, String data)
{
LinkedListNode newNode;
newNode = new LinkedListNode(data);
newNode.next = spot.next;
spot.next = newNode;
}//end addAfter
public void addBefore(LinkedListNode spot, String data)
{
}//end addBefore
public void deleteAfter(LinkedListNode spot)
{
LinkedListNode nextNode;
nextNode = spot.next;
spot.next = nextNode.next;
}//end deleteAfter
public String showList()
{
sortList();
//^-- Will sort the sum but not the nodes
int i = 0;
String retStr = "The nodes in the list are:\n";
LinkedListNode current = front;
while(current != null){
i++;
retStr += "Node " + i + " is: " + current.getData() + " and the sum is: " + current.getSum() + "\n";
current = current.getNext();
}
return retStr;
}
public LinkedListNode findTail()
{
LinkedListNode current = front;
while(current.getNext() != null){
current = current.getNext();
}
return current;
}//end findTail
public LinkedList sortList()
{
LinkedListNode current = front;
LinkedListNode tail = null;
while(current != null && tail != front )
{
LinkedListNode next = current;
for( ; next.next != tail; next = next.next)
{
if(next.sum >= next.next.sum)
{
long temp = next.sum;
String temp2 = next.data;
next.sum = next.next.sum;
next.data = next.next.data;
next.next.sum = temp;
next.next.data = temp2;
}
}
tail = next;
current = front;
}
return this;
}
public void removeNode(){
String searchedNode;
Scanner in = new Scanner(System.in);
System.out.println("Enter the name you would like to remove from the list: ");
searchedNode = in.nextLine();
in.close();
LinkedListNode previous = null;
LinkedListNode current = front;
//while there is something in the list nodes
while (current != null)
{
//if the data of current is equal to the node being searched
if(current.data.equals(searchedNode))
{
//set current to the node after current
current = current.next;
//if previous is equal to null(which it is)
if (previous == null)
{
//set previous equal to current
previous = current;
}
else previous.next = current;
} else {
previous = current;
current = current.next;
}
} //end while
}
}
fileIn class:
import java.util.Scanner;
import java.io.*;
public class fileIn
{
LinkedListNode front;
LinkedList myList = new LinkedList();
String fname;
public static void main(String[] args)
{
fileIn f = new fileIn();
}//end main
public fileIn()
{
getFileName();
readFileContents();
System.out.print(myList.showList());
myList.removeNode();
}//end fileIn
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
/* Read input from file and process. */
try
{
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping)
{
/* Get a line of input from the file. */
if (null == (line = in.readLine()))
{
looping = false;
/* Close and free up system resource. */
in.close();
}//end if
else
{
myList.insertBack(line);
}//end else
} /* End while. */
} /* End try. */
catch(IOException e)
{
System.out.println("Error " + e);
} /* End catch. */
}//end readFileContents
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
in.close();
}//end getFileName
}//end class fileIn
The problem is you are closing System.in (Scanner.close() closes the underlying stream). Once you do that, it stays closed, and is unavailable for input. You don't normally want to do that with standard input:
String searchedNode;
Scanner in = new Scanner(System.in);
System.out.println("Enter the name you would like to remove from the list: ");
searchedNode = in.nextLine();
// in.close(); // <-- don't close standard input!
Also, for future reference, you should try to create more minimal test cases. It will help you debug and also remove a lot of noise from your questions. :-)
As per How to solve java.util.NoSuchElementException in Java (as well as common sense) use the appropriate kind of hasNext method before each next.
In your particular case, it will be something like this:
if (in.hasNextLine) {
in.nextLine();
}

Append two linked list

I wrote a simple method to append a linked list at the end of another linked list.So what the program should ideally do is when I give it two lists
list1 ===>1->2->3
list2 ===>4->5->6
updatedList ==>1->2->3->4->5->6
But when I run the method appendList it goes into an infinite loop printing 1 to 6 indefinitely.What am I doing wrong out here?
public static Node appendList(Node head1, Node head2) {
Node prev = null;
Node current = head1;
while (current != null) {
prev = current;
current = current.next;
}
prev.next = head2;
return head1;
}
Oh and I forgot to add the Node class and how I call the method from my main .I know its bit cumbersome but here it is
public class ReverseLinkedList {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
public void displayData() {
System.out.println(data);
}
}
public static void main(String args[]) {
ReverseLinkedList reversedList = new ReverseLinkedList();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of the linked list!!");
int listSize = scanner.nextInt();
System.out.println("Enter the Numbers you want to insert!!");
int count = 0;
while (scanner.hasNextLine()) {
if (count == listSize)
break;
reversedList.insert(scanner.nextInt());
count++;
}
System.out.println("Inserted List !!");
reversedList.displayList();
/*
* Node reverseNodeStart =
* reversedList.reverseList1(reversedList.first);
* System.out.println("Reversed List !!"); while (reverseNodeStart !=
* null) { reverseNodeStart.displayData(); reverseNodeStart =
* reverseNodeStart.next; }
*/
Node reverseNodeStart = reversedList.appendList(reversedList.first,
reversedList.first);
while (reverseNodeStart != null) {
reverseNodeStart.displayData();
reverseNodeStart = reverseNodeStart.next;
}
}
}
The problem was I was using the same List which was causing the circular reference.It works fine now.You knew the problem even before I posted the code now that's impressive. Thanks!!I solved it by creating a new List2 and passing in List1 and List2.
appendList(Node lis1head, Node list2head)

Categories

Resources