SlideShare a Scribd company logo
I need help implementing a Stack with this java programming assignment:
Given a doubly linked list (code provided below) implement a Stack. You must use the doubly
link list class and utilize it as an object in your implementation of the stack.
A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the
last element which was inputted in the collection. The Stack is based on the process of putting
things on top of one another and taking the item on top (think of a stack of papers).
Operations to implement:
push (E): Add an element to the start of the sequence
pop: Remove an element from the start of the sequence
Peek: Return the first element of the sequence without removing it
atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound
(if you can control the user input then do that instead)
Size: Return the size of the Stack
isEmpty: Boolean, returns true if the Stack is empty
Empty: Empty the Stack
Code Part 1:
public class DoublyLinkedList{
private DNode head;
private DNode tail;
private int size;
public DoublyLinkedList(){ // construct an empty list
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
this.size = 0;
}
public DoublyLinkedList(DNode next){ // constructs a list
// out of a single node
this.tail = new DNode (null, null, next);
this.head = new DNode (null, next, null);
next.changeNext(this.tail);
next.changePrev(this.head);
this.size = 1;
}
public DoublyLinkedList(Object [] objectArray){ // construct a list out of
// an array
this.tail = new DNode (null, null, this.head);
this.head = new DNode (null, this.tail, null);
DNode temp = this.head;
for (Object e : objectArray)
{
//Anonomus function
new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext());
temp = temp.getNext();
this.size += 1;
}
}
public void addToFrontofList(Object toAdd){ // Appends the begining
// of the list
DNode temp = new DNode (toAdd, this.head.getNext(), this.head);
this.head.getNext().changePrev(temp);
this.head.changeNext(temp);
this.size += 1;
}
public void addToendofList (Object toAdd) // appends the end of the list
// with a node
{
DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev());
this.tail.getPrev().changeNext(temp);
this.tail.changePrev(temp);
this.size += 1;
}
public void insertAfterNode(DNode current, Object input)// Inserts a new
// a new node after
// current node
{
current.insertAfterNode(input);
this.size += 1;
}
public int getSize() // returns the size of the list
{
return this.size;
}
public String toString()
{
String result = "";
for (DNode temp = this.head.getNext();
temp.hasNext(); temp = temp.getNext())
{
result += temp.getValue();
result += " -> ";
}
result += "End of list";
return result;
}
}
and code part2:
public class DNode{
private Object e; // place holder for the type of object the
//collection is storing
private DNode next; // reference to the next node in the sequence
// of nodes making up the linked list. Remember
// that even though Java passes Objects by value
// an object consisting of reference will behave
// the same as an object passed by reference unless
// a deep copy was made.
private DNode prev;
public DNode(Object e){ // Constructor for implementing a single node
this.e = e; // The value of the element to be assigned to
// this particular instance of node
this.next = null; // An empty reference since there is no node
// to follow.
this.prev = null;
}
public DNode(Object e, DNode next, DNode prev){ // Constructor for
//implementing a node that
//comes after another node
this.e = e; // The value of the element to be assigned to
// this particular instance of node
this.next = next; // reference to the subsequent node to follow
this.prev = prev;
}
public void changeNext(DNode next){ // Changes the link to the next node
this.next = next;
}
public void changePrev(DNode prev){ // Changes the link to the next node
this.prev = prev;
}
public DNode getNext(){ // Returns the node next in the sequence
return this.next;
}
public Object getValue(){ // Returns the value a node is holding
return this.e;
}
public Boolean hasNext(){ // Returns a boolean determining regarding
// the status of subsequent nodes after
// the current node
return !(this.next.getValue() == null || this.next == null);
}
public Boolean hasprev(){ // Returns a boolean determining regarding
// the status of subsequent nodes after
// the current node
return !(this.prev.getValue() == null || this.prev == null);
}
public void insertAfterNode( Object input){
this.changeNext(new DNode (input, this.getNext(), this));
}
public void insertAfterNode(DNode input){
this.changeNext(input);
input.changeNext(this.next);
input.changePrev(this);
}
public void insertbeforeNode(DNode input){
this.changeNext(input);
}
public void insertBetweenNodes(DNode before, DNode after){
this.changeNext(after);
this.changePrev(before);
before.changeNext(this);
after.changePrev(this);
}
public DNode getPrev(){
return this.prev;
}
}
Solution
Following is the program that contain functions like push,pop,isEmpty etc. call this function with
proper data.
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
// this class keeps track all element info
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
// returns the size of the linked list
public int size() { return size; }
// return whether the list is empty or not
public boolean isEmpty() { return size == 0; }
// adds element at the starting of the linked list
public void push(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println("adding: "+element);
}
// this method removes element from the start of the linked list
public E pop() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println("deleted: "+tmp.element);
return tmp.element;
}
public E Peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return head.element;
}
public void remove()
{
head = null;
}
// Takes index as argument and return data at index
public E GetNth(int index)
{
Node current = head;
int count = 0;
while (current != null)
{
if (count == index)
return current.element;
count++;
current = current.next;
}
assert(false);
return current.element;
}
public static void main(String a[]){
// Testing data to test the functions
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.remove();
dll.push(10);
dll.push(34);
dll.size();
dll.Peek();
dll.GetNth(2);
dll.pop();
}
}

More Related Content

Similar to I need help implementing a Stack with this java programming assignme.pdf (20)

PDF
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
PDF
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
mail931892
 
PDF
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
PDF
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
ChristopherkUzHunter
 
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
PPT
Jhtp5 20 Datastructures
martha leon
 
PDF
In the class we extensively discussed a generic singly linked list i.pdf
birajdar2
 
PDF
210 Linked-llists of data structure with .pdf
AhsanRamzan7
 
PDF
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
PDF
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
facevenky
 
PDF
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
sauravmanwanicp
 
PDF
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
PDF
Doubly Link List
Kashif Memon
 
PDF
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
PDF
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
rozakashif85
 
PDF
Rewrite this code so it can use a generic type instead of integers. .pdf
alphaagenciesindia
 
PDF
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
mail931892
 
PDF
Fix my codeCode.pdf
Conint29
 
PDF
This is a homework assignment that has to be done in JAVA.Objectiv.pdf
feelingcomputors
 
PDF
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
mail931892
 
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
ChristopherkUzHunter
 
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
Jhtp5 20 Datastructures
martha leon
 
In the class we extensively discussed a generic singly linked list i.pdf
birajdar2
 
210 Linked-llists of data structure with .pdf
AhsanRamzan7
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
facevenky
 
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
sauravmanwanicp
 
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
Doubly Link List
Kashif Memon
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
rozakashif85
 
Rewrite this code so it can use a generic type instead of integers. .pdf
alphaagenciesindia
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
mail931892
 
Fix my codeCode.pdf
Conint29
 
This is a homework assignment that has to be done in JAVA.Objectiv.pdf
feelingcomputors
 
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 

More from sauravmanwanicp (20)

PDF
Are hydrophobic interactions weak or strongSolutionHydrophobi.pdf
sauravmanwanicp
 
PDF
What is another word for account based forecast What is anothe.pdf
sauravmanwanicp
 
PDF
What function can be used to return multiple numeric data such as in.pdf
sauravmanwanicp
 
PDF
Answer the following questions in reference to Drosophila melanogast.pdf
sauravmanwanicp
 
PDF
There are five feasible solutions to a three-objective optimization p.pdf
sauravmanwanicp
 
PDF
An air-filled parallel-plate capacitor has capacitance Co. If two ide.pdf
sauravmanwanicp
 
PDF
The incandescent lightbulb was actually invented by Humphry Davy in 1.pdf
sauravmanwanicp
 
PDF
The fossil record provides little information about ancient mosses. D.pdf
sauravmanwanicp
 
PDF
The DNA sequence below is a shortened version of the sequence on the .pdf
sauravmanwanicp
 
PDF
the conducting tissue found in vascular plants that functions in tra.pdf
sauravmanwanicp
 
PDF
Show that f(x)=57^x+1 and f^-1(x)=7x-75 are inverses Choose the ap.pdf
sauravmanwanicp
 
PDF
Read the short article Horizontal Gene Transfer in E Coli and answer.pdf
sauravmanwanicp
 
PDF
Please select the best answer and click submit. The owners of fou.pdf
sauravmanwanicp
 
PDF
One function of the spliceosome is to (Select all that apply.)A. .pdf
sauravmanwanicp
 
PDF
Match the following organelles with their key functions in the cell .pdf
sauravmanwanicp
 
PDF
please choose the correct answerIn the ABO blood-type phenotype, w.pdf
sauravmanwanicp
 
PDF
mo Press Submit until all questions are colored green and you have do.pdf
sauravmanwanicp
 
PDF
matching chose the stage of the light reactions which the statement.pdf
sauravmanwanicp
 
PDF
Let E be the set of all even integers, and let O be the set of all o.pdf
sauravmanwanicp
 
PDF
JavaIm not sure how to implement this code can someone help me .pdf
sauravmanwanicp
 
Are hydrophobic interactions weak or strongSolutionHydrophobi.pdf
sauravmanwanicp
 
What is another word for account based forecast What is anothe.pdf
sauravmanwanicp
 
What function can be used to return multiple numeric data such as in.pdf
sauravmanwanicp
 
Answer the following questions in reference to Drosophila melanogast.pdf
sauravmanwanicp
 
There are five feasible solutions to a three-objective optimization p.pdf
sauravmanwanicp
 
An air-filled parallel-plate capacitor has capacitance Co. If two ide.pdf
sauravmanwanicp
 
The incandescent lightbulb was actually invented by Humphry Davy in 1.pdf
sauravmanwanicp
 
The fossil record provides little information about ancient mosses. D.pdf
sauravmanwanicp
 
The DNA sequence below is a shortened version of the sequence on the .pdf
sauravmanwanicp
 
the conducting tissue found in vascular plants that functions in tra.pdf
sauravmanwanicp
 
Show that f(x)=57^x+1 and f^-1(x)=7x-75 are inverses Choose the ap.pdf
sauravmanwanicp
 
Read the short article Horizontal Gene Transfer in E Coli and answer.pdf
sauravmanwanicp
 
Please select the best answer and click submit. The owners of fou.pdf
sauravmanwanicp
 
One function of the spliceosome is to (Select all that apply.)A. .pdf
sauravmanwanicp
 
Match the following organelles with their key functions in the cell .pdf
sauravmanwanicp
 
please choose the correct answerIn the ABO blood-type phenotype, w.pdf
sauravmanwanicp
 
mo Press Submit until all questions are colored green and you have do.pdf
sauravmanwanicp
 
matching chose the stage of the light reactions which the statement.pdf
sauravmanwanicp
 
Let E be the set of all even integers, and let O be the set of all o.pdf
sauravmanwanicp
 
JavaIm not sure how to implement this code can someone help me .pdf
sauravmanwanicp
 
Ad

Recently uploaded (20)

PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Ad

I need help implementing a Stack with this java programming assignme.pdf

  • 1. I need help implementing a Stack with this java programming assignment: Given a doubly linked list (code provided below) implement a Stack. You must use the doubly link list class and utilize it as an object in your implementation of the stack. A Stack is a Last in First Out (LiFO) structure which translates to the processes of outputting the last element which was inputted in the collection. The Stack is based on the process of putting things on top of one another and taking the item on top (think of a stack of papers). Operations to implement: push (E): Add an element to the start of the sequence pop: Remove an element from the start of the sequence Peek: Return the first element of the sequence without removing it atIndex(x): Return the element at the given index (x) Or throw an exception if it is out of bound (if you can control the user input then do that instead) Size: Return the size of the Stack isEmpty: Boolean, returns true if the Stack is empty Empty: Empty the Stack Code Part 1: public class DoublyLinkedList{ private DNode head; private DNode tail; private int size; public DoublyLinkedList(){ // construct an empty list this.tail = new DNode (null, null, this.head); this.head = new DNode (null, this.tail, null); this.size = 0; } public DoublyLinkedList(DNode next){ // constructs a list // out of a single node this.tail = new DNode (null, null, next); this.head = new DNode (null, next, null); next.changeNext(this.tail); next.changePrev(this.head); this.size = 1; } public DoublyLinkedList(Object [] objectArray){ // construct a list out of
  • 2. // an array this.tail = new DNode (null, null, this.head); this.head = new DNode (null, this.tail, null); DNode temp = this.head; for (Object e : objectArray) { //Anonomus function new DNode (e, temp.getNext(),temp).insertBetweenNodes(temp, temp.getNext()); temp = temp.getNext(); this.size += 1; } } public void addToFrontofList(Object toAdd){ // Appends the begining // of the list DNode temp = new DNode (toAdd, this.head.getNext(), this.head); this.head.getNext().changePrev(temp); this.head.changeNext(temp); this.size += 1; } public void addToendofList (Object toAdd) // appends the end of the list // with a node { DNode temp = new DNode (toAdd, this.tail, this.tail.getPrev()); this.tail.getPrev().changeNext(temp); this.tail.changePrev(temp); this.size += 1; } public void insertAfterNode(DNode current, Object input)// Inserts a new // a new node after // current node { current.insertAfterNode(input); this.size += 1; } public int getSize() // returns the size of the list
  • 3. { return this.size; } public String toString() { String result = ""; for (DNode temp = this.head.getNext(); temp.hasNext(); temp = temp.getNext()) { result += temp.getValue(); result += " -> "; } result += "End of list"; return result; } } and code part2: public class DNode{ private Object e; // place holder for the type of object the //collection is storing private DNode next; // reference to the next node in the sequence // of nodes making up the linked list. Remember // that even though Java passes Objects by value // an object consisting of reference will behave // the same as an object passed by reference unless // a deep copy was made. private DNode prev; public DNode(Object e){ // Constructor for implementing a single node this.e = e; // The value of the element to be assigned to // this particular instance of node this.next = null; // An empty reference since there is no node // to follow. this.prev = null; }
  • 4. public DNode(Object e, DNode next, DNode prev){ // Constructor for //implementing a node that //comes after another node this.e = e; // The value of the element to be assigned to // this particular instance of node this.next = next; // reference to the subsequent node to follow this.prev = prev; } public void changeNext(DNode next){ // Changes the link to the next node this.next = next; } public void changePrev(DNode prev){ // Changes the link to the next node this.prev = prev; } public DNode getNext(){ // Returns the node next in the sequence return this.next; } public Object getValue(){ // Returns the value a node is holding return this.e; } public Boolean hasNext(){ // Returns a boolean determining regarding // the status of subsequent nodes after // the current node return !(this.next.getValue() == null || this.next == null); } public Boolean hasprev(){ // Returns a boolean determining regarding // the status of subsequent nodes after // the current node return !(this.prev.getValue() == null || this.prev == null); } public void insertAfterNode( Object input){ this.changeNext(new DNode (input, this.getNext(), this)); } public void insertAfterNode(DNode input){ this.changeNext(input);
  • 5. input.changeNext(this.next); input.changePrev(this); } public void insertbeforeNode(DNode input){ this.changeNext(input); } public void insertBetweenNodes(DNode before, DNode after){ this.changeNext(after); this.changePrev(before); before.changeNext(this); after.changePrev(this); } public DNode getPrev(){ return this.prev; } } Solution Following is the program that contain functions like push,pop,isEmpty etc. call this function with proper data. import java.util.NoSuchElementException; public class DoublyLinkedListImpl { private Node head; private Node tail; private int size; public DoublyLinkedListImpl() { size = 0; } // this class keeps track all element info private class Node { E element; Node next;
  • 6. Node prev; public Node(E element, Node next, Node prev) { this.element = element; this.next = next; this.prev = prev; } } // returns the size of the linked list public int size() { return size; } // return whether the list is empty or not public boolean isEmpty() { return size == 0; } // adds element at the starting of the linked list public void push(E element) { Node tmp = new Node(element, head, null); if(head != null ) {head.prev = tmp;} head = tmp; if(tail == null) { tail = tmp;} size++; System.out.println("adding: "+element); } // this method removes element from the start of the linked list public E pop() { if (size == 0) throw new NoSuchElementException(); Node tmp = head; head = head.next; head.prev = null; size--; System.out.println("deleted: "+tmp.element); return tmp.element; } public E Peek() {
  • 7. if (isEmpty()) throw new NoSuchElementException("Stack underflow"); return head.element; } public void remove() { head = null; } // Takes index as argument and return data at index public E GetNth(int index) { Node current = head; int count = 0; while (current != null) { if (count == index) return current.element; count++; current = current.next; } assert(false); return current.element; } public static void main(String a[]){ // Testing data to test the functions DoublyLinkedListImpl dll = new DoublyLinkedListImpl(); dll.remove(); dll.push(10); dll.push(34); dll.size(); dll.Peek(); dll.GetNth(2); dll.pop(); } }