In: Computer Science
Program Language C++
How do I take lines of string from an input file, and implement them into a stack using a double linked list? Example input, command.txt, and output file.
Ex:
Input.txt
postfix: BAC-*
prefix:+A*B/C-EF
postfix:FE-C/B*A+
postfix:AB-C-D/
postfix:AB-CF*-D / E+
Command.txt
printList
printListBackwards
Output.txt
List:
postfix:BAC-*
prefix:+A*B/C-EF
postfix:FE-C/B*A+
postfix:AB-C-D/
postfix:AB-CF*-D/E+
Reversed List:
postfix:AB-CF*-D/E+
postfix:AB-C-D/
postfix:FE-C/B*A+
prefix:+A*B/C-EF
postfix:BAC-*
//package frame;
import java.io.*;
import java.util.*;
public class Dlink{
public static Node h=null; // h of list
//Doubly Linked list N
public static class Node {
String d;
Node p;
Node nxt;
Node(String d1) { d = d1; } // Constructor to create a new N
}
public static void push(String new_d) // Adding a N at the front of
the list
{
Node nw = new Node(new_d);//allocate N
nw.nxt = h; //Make nxt of new N as h and pious as NULL
nw.p = null;
if (h != null) //change p of h N to new N
h.p = nw;
h = nw; //move the h to point to the new N
}
public static void append(String new_d) // Add a N at the end of
the list
{
Node nw = new Node(new_d); //allocate N
Node l = h;
nw.nxt = null; //This new N is going to be the l N, so make nxt of
it as NULL
if (h == null) { //If the Linked List is empty, then make the new N
h
nw.p = null;
h = nw;
return;
}
while (l.nxt != null){ //Else traverse till the l N
l = l.nxt; }
l.nxt = nw; //Change the nxt of l N
nw.p = l; //Make l N as pious of new N
}
public void printlist(Node node) // This function prints contents
of linked list starting from the given N
{
Node l = null;
while (node != null) {
System.out.println(node.d + " ");
l = node;
node = node.nxt;
}
System.out.println();
System.out.println("Reverse direction");
while (l != null) {
System.out.println(l.d + " ");
l = l.p;
}
}
public static void main(String[] args) throws
FileNotFoundException
{
Dlink dll = new Dlink(); //Start with the empty list
ArrayList<String> lt= new ArrayList<String>(); //Start
with the empty list
try (BufferedReader br = new BufferedReader(new
FileReader("data.txt"))) //opening the file
{
String CLine;//variable
while ((CLine = br.readLine()) != null) {//read line by line
lt.add(CLine);//add the line to list
}
} catch (IOException e) {
e.printStackTrace();//catch the error if file not found
}
push(lt.get(0));
int ct = 1;
while (lt.size() > ct) {//traverse through arraylist
append(lt.get(ct));//printing result
//System.out.println(lt.get(ct));
ct++;
}
System.out.println("Created DLL is: ");
dll.printlist(dll.h); //printing the List
}
}
If you found this answer helpful please give a thumbs up.