I need to implement both a Queue and ArrayList by using an internal LinkedList. I created my DoublyLinkedList class and was able to implement it into my queue with no problem. The problem I am running into is that to add or delete to/from the ArrayList, the add/delete methods take in a integer for the index and an object/element. All my methods inside my DoublyLinkedList class take in either elements and/or Nodes.
My question is this, how can I implement my DoublyLinkedList methods inside my ArrayList when my DLL class doesn't take any int values in.
I want to be able to add or delete the node by using the index, but I can't. Realistically, I would want something like list.addAfter(I) without I being an integer.
Note: The goal of this assignment is to implement ADTs, so I can't modify the method signatures of the ArrayList ADT.
DoublyLinedList Class
public class DoublyLinkedList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public DoublyLinkedList() {
this.head = new Node<E>(null, null, null);
this.tail = new Node<E>(null, null, null);
this.size = 0;
head.setNext(tail);
tail.setPrev(head);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Node<E> getPrev(Node<E> n) {
return n.getPrev();
}
public Node<E> getNext(Node<E> n) {
return n.getNext();
}
public Node<E> getFirst() {
return head.getNext();
}
public Node<E> getLast() {
return tail.getPrev();
}
public E remove(Node<E> c) {
Node<E> a = c.getPrev();
Node<E> b = c.getNext();
b.setNext(a);
a.setPrev(b);
c.setNext(null);
c.setPrev(null);
size--;
return c.getElement();
}
public E removeFirst() {
return remove(head.getNext()); // first element is beyond header
}
public E removeLast() {
return remove(tail.getPrev());
}
public void addBefore(Node<E> node, E e) {
Node<E> prev = getPrev(node);
Node<E> n = new Node<E>(e, prev, node);
node.setPrev(n);
prev.setNext(n);
size++;
}
public void addFirst(E e) {
addAfter(head, e);
}
public void addLast(E e) {
addBefore(tail, e);
}
public void addAfter(Node<E> node, E e) {
Node<E> next = getNext(node);
Node<E> n = new Node<E>(e, node, next);
node.setNext(n);
next.setPrev(n);
size++;
}
}
LArrayList class (my Arraylist implementation)
public class LArrayList implements List {
private DoublyLinkedList list;
private int size;
public LArrayList() {
this.list = new DoublyLinkedList();
this.size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int I, Object e) throws IndexOutOfBoundsException {
if (isEmpty()) {
list.addFirst(e);
}
// HERE IS MY CONCERN. THESE FOUR METHODS ALL TAKE IN INT VALUES WHILE
// NON OF MY DLL METHODS DO!
}
public Object get(int i) throws IndexOutOfBoundsException {
return null;
}
public Object remove(int i) throws IndexOutOfBoundsException {
return null;
}
public Object set(int I, Object e) throws IndexOutOfBoundsException {
return null;
}
}
It seems like a fairly easy thing to do - just use the API exposed by your LinkedList and add some logic to it. Here is the bit you are missing
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = list.getNext(node);
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
list.addBefore(node, e);
this.size++;
I do have to note that your LinkedList implementation can be improved - first of all, the getPrev() getNext() addBefore() and addAfter() should be static, as you shouldn't have to use a LinkedList instance to call them. However, it would be even better if the methods were actually methods in Node, because that way the traversal and usage of the LinkedList would be way more easy. Here is how the above code would look like if the methods were in Node:
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = node.getNext();
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
node.addBefore(e);
this.size++;
You pretty much do not need the list at all - certainly you don't need to just pass extra parameters to some functions. You can still keep the (hopefully static) methods in Linked list that do the same thing, but they'd just be proxies for the Node implementation of the methods, e.g.:
public static void addAfter(Node<E> node, E e) {
node.addAfter(e);
}
I am not sure if you will need these methods in LinkedList but they can certainly be there for "backwards compliance", if you will.
EDIT Forgot to mention - the fist bit of code is the implementation for add(), I am sure you can work out the rest, as they'd do the same thing.
public Object get(int i) throws IndexOutOfBoundsException {
if(list.size()<=i) throw new IndexOutOfBoundsException();
Node current = list.getFirst();
for(int x = 0; x<=i; x++){
if(x == i) return current.getElement();//Change this behaviour for remove and set
current = current.getNext();
}
}
Related
I'm trying to make a generic stack and queue class that uses the generic node class. It has empty(), pop(), peek(), push(), and a search() method. I know there is a built-in Stack class and stack search method but we have to make it by using the Node class.
I am unsure of how to make the search method. The search method is supposed to return the distance from the top of the stack of the occurrence that is nearest the top of the stack. The topmost item is considered to be at distance 1; the next item is at distance 2; etc.
My classes are below:
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
private Node<E> head;
private int nodeCount;
public static void main(String args[]) {
}
public E peek() {
return this.head.getData();
}
public E pop() {
E item;
item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head==null) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
// todo
}
}
public class Node<E>
{
E data;
Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
public class MyQueue<E> implements QueueInterface<E>
{
private Node<E> head;
private int nodeCount;
Node<E> rear;
public MyQueue()
{
this.head = this.rear = null;
}
public void add(E item){
Node<E> temp = new Node<E>(item);
if (this.rear == null) {
this.head = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public E peek(){
return this.head.getData();
}
public E remove(){
E element = head.getData();
Node<E> temp = this.head;
this.head = this.head.getNext();
nodeCount--;
return element;
}
}
After working on it based off of the first comment I have this:
public int search(Object o){
int count=0;
Node<E> current = new Node<E> (head.getData());
while(current.getData() != o){
current.getNext();
count++;
}
return count;
}
It doesn't have any errors but I cannot tell if it is actually working correctly. Does this seem correct?
It needs the following improvements,
search method should have parameter of type 'E'. So, the signature should look like public int search(E element)
start the count with 1 instead of 0.As you have mentioned topmost item is considered to be at distance 1
initialize current with head, because creating a new node with data value of head(new node(head.getData())) will create an independent node with data same as head node; and the while will run only for the head node as current.getNext() will be null always. Node<E> current = head will create another reference variable pointing to the head.
Instead of != in condition, use if( !current.getData().equals(element.getData())) )
If using your own class as data type, don't forget to override equals method.
Change current.getNext(); to current = current.getNext();
You have problems with other method. Pay attention on top == null. To calculate search() all you need is just iterate over the elements and find position of required value:
public class MyStack<E> {
private Node<E> top;
private int size;
public void push(E val) {
Node<E> node = new Node<>(val);
node.next = top;
top = node;
size++;
}
public E element() {
return top == null ? null : top.val;
}
public E pop() {
if (top == null)
return null;
E val = top.val;
top = top.next;
size--;
return val;
}
public boolean empty() {
return size == 0;
}
public int search(E val) {
int res = 1;
Node<E> node = top;
while (node != null && node.val != val) {
node = node.next;
res++;
}
return node == null ? -1 : res;
}
private static final class Node<E> {
private final E val;
private Node<E> next;
public Node(E val) {
this.val = val;
}
}
}
I assume your MyStack class should be compatible with the Stack class provided by Java as you mention it in your question. This means that your signature public int search(Object o) matches the signature of java.util.Stack#search (apart from synchronised).
To implement the search method using your Node class, we need to traverse the stack and return the index of the first (uppermost) match. First, assign head to a local variable (current). Then you can create a loop where you current.getNext() at the end to get the next element. Stop if the next element is null as we have reached the end of the stack. In the loop, you either count up the index or return this index when the current element's data matches the argument o.
The evaluation needs to be able to deal with null values for your argument o. Therefore, you need to check for null first and adjust your logic accordingly. When o is null, do a null-check against current.getData(). If o is not null, check if current.getData() is equal to o with equals().
Here is a working example: (compatible with java.util.Stack#search)
public int search(Object o) {
int index = 1;
Node<E> current = head;
while (current != null) {
if (o == null) {
if (current.getData() == null) {
return index;
}
} else {
if (o.equals(current.getData())) {
return index;
}
}
current = current.getNext();
index++;
}
return -1; // nothing found
}
To test this, you can write a simple unit test with JUnit like this:
#Test
public void testMyStackSearch() {
// initialize
final MyStack<String> stack = new MyStack<>();
stack.push("e5");
stack.push("e4");
stack.push(null);
stack.push("e2");
stack.push("e1");
// test (explicitly creating a new String instance)
assertEquals(5, stack.search(new String("e5")));
assertEquals(3, stack.search(null));
assertEquals(2, stack.search(new String("e2")));
assertEquals(1, stack.search(new String("e1")));
assertEquals(-1, stack.search("X"));
}
Since you have already a reference implementation, you can replace MyStack with Stack (java.util.Stack) and see if your asserts are correct. If this runs successfully, change it back to MyStack and see if your implementation is correct.
Note: I do not recommend to actually use the Stack implementation in Java. Here, it just serves as a reference implementation for the java.util.Stack#search method. The Deque interface and its implementations offer a more complete and consistent set of LIFO stack operations, which should be used in preference to Stack.
I'm having trouble figuring out why my code won't parse through the ListNodes in the Lists, in order to add a new String as a ListNode. I'm trying to write the function add(String s), to add a new ListNode to the List. If the list is empty, I just add the String as a ListNode, and if not, I parse through using node and myNext, and then if node.myNext is null, I replace it with the newly created ListNode. What is the reason this isn't working? It either does not throw an output or it says it is out of bounds.
public class List {
private ListNode myHead;
private int mySize;
public List() {
this.myHead = null;
this.mySize = 0;
}
public class ListNode {
public String myData;
public ListNode myNext;
public ListNode(String element, ListNode next) {
this.myData = element;
this.myNext = next;
}
public ListNode(String element) {
this(element, null);
}
public boolean isEmpty() {
return this.length() == 0;
}
public void add(String s) {
if(this.isEmpty() == true) {
this.addToFront(s);
}
else {
this.mySize++;
for(ListNode node = this.myHead; node.myData != null; node = node.myNext) {
if(node.myNext == null) {
ListNode lno = new ListNode(s, null);
node.myNext = lno;
}
else {
node.myData = node.myData;
}
}
}
}
In you ListNode you can't access methods and variables of your List class.
Assuming that you want to add the new String at the top of your List you should do something like this:
public class List {
private ListNode myHead;
private int mySize;
public List() {
this.myHead = null;
this.mySize = 0;
}
public boolean isEmpty() {
return this.mySize == 0;
}
public void add(String s) {
this.myHead = new ListNode(s, myHead);//add new String as head element
this.mySize++;
}
}
public class ListNode {
public String myData;
public ListNode myNext;
public ListNode(String element, ListNode next) {
this.myData = element;
this.myNext = next;
}
public ListNode(String element) {
this(element, null);
}
}
If you want to add it at the end of your List you can try it like this:
public void add(String s) {
if(this.isEmpty()){
this.myHead = new ListNode(s, myHead);//add new String as head element
}else{
ListNode node = this.myHead;
while (node.myNext != null){
node = node.myNext;
}
//now you hav the last node of your list
node.myNext = new ListNode(s,null);
}
this.mySize++;
}
The code you have pasted is not complete.
Also, If I am correct, your List is having the ListNodes and thus, it is your List where you should put methods to check if it is Empty (does not have any ListNodes in it) or add, delete, count, search etc. functions.
For isEmpty(), There is no length() defined, so simply check the size to be == 0.
For add(), if it is empty just point myHead to your new ListNode; If you have to add in end, iterate the myHead using a currentNode reference, till its next is null and add.
If it is to be in middle somewhere, you will need to check for ListNode myData to decide where it fits white moving from myHead towards null and once you find a place to insert, you will need to change the [PrevNode] -> new ListNode -> [nextNode]
The classes are not complete, but here's what I have so far and I expected the test below to pass.
public class LinkedList<T> extends AbstractSequentialList<T> {
private Node<T> head;
#Override
public boolean add(T element) {
if(head == null) {
head = new Node(element);
}
return true;
}
#Override
public ListIterator<T> listIterator(int index) {
return new LinkedListIterator<>();
}
#Override
public int size() {
return 0;
}
private class LinkedListIterator<T> implements ListIterator<T> {
private Node<T> current;
public LinkedListIterator() {
current = (Node<T>) head;
}
#Override
public boolean hasNext() {
return (current != null && current.getNext() != null)? true : false;
}
#Override
public T next() {
return null;
}
}
}
Here is the Node class.
public class Node<T> {
private T value;
private Node next;
public Node(T value) {
this.value = value;
}
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
My iterator test is like this.
LinkedList<String> list;
ListIterator<String> iterator;
#Before
public void setUp() throws Exception {
list = new LinkedList<>();
iterator = list.listIterator();
}
#Test
public void testHasNext() throws Exception {
assertThat(iterator.hasNext(), is(false));
list.add("Hello World");
assertThat(iterator.hasNext(), is(true));
}
However, I'm failing on the second assertion. My issue is that the "current" pointer in the iterator is always null even though I'm setting it to the head of the enclosing LinkedList class. How can I fix this? Thanks.
It looks the value of current is set inside the constructor of LinkedListIterator.
It hasn't been updated after you have added an element to the list. This seems to your problem here.
What is wrong is your test, IMO.
You shouldn't expect the iterator to point to the first element if the first element has been added after the iterator has been constructed.
Now, why does your iterator work this way? Because Java is pass-by-value. When you construct an iterator, the iterator receives a copy of the reference to the first node of the list. And at this time, this reference is null, because you haven't added any node yet.
If you really want the iterator to "see" the first node of the list even after it has been constructed, then the iterator needs to get the first node of the list in hasNext(), not in the constructor.
So the task is to implement a linked-list and merge-sort which sorts linked-lists. I am fully aware that in industry I most likely won't have to implement any of these but I feel it's a good way to practice Java. Here is what I've got up to this point:
Node class:
public class Node<E extends Comparable<E>>
{
public E data;
public Node<E> next;
public Node(E data)
{
this.data = data;
next = null;
}
public void printData()
{
System.out.print(data + " ");
}
}
LinkedList class:
public class LinkedList<E extends Comparable<E>>
{
protected Node<E> root;
protected int size = 0;
public LinkedList()
{
root = null;
}
public void addBeg(E e)
{
Node<E> newNode = new Node<E>(e);
newNode.next = root;
root = newNode;
size++;
}
public Node deleteBeg()
{
Node<E> temp = root;
if(!isEmpty())
{
root = root.next;
size--;
}
return temp;
}
public void setRoot(Node<E> newRoot)
{
root = newRoot;
}
public boolean isEmpty()
{
return root == null;
}
public Node<E> getRoot()
{
return root;
}
public void printList()
{
Node<E> cur = root;
while(cur!=null)
{
cur.printData();
cur=cur.next;
}
System.out.println();
}
}
MergeSorter Class:
public class MergeSorter<E extends Comparable<E>>
{
public MergeSorter()
{
}
private void split(LinkedList<E> list, LinkedList<E> firHalf, LinkedList<E> secHalf)
{
//if 0 or only 1 elements in the list - it doesn't seem to work, however
if(list.getRoot() == null || list.getRoot().next == null)firHalf = list;
else{
Node<E> slow = list.getRoot();
Node<E> fast = list.getRoot().next;
while(fast!=null)
{
fast = fast.next;
if(fast!=null)
{
fast = fast.next;
slow = slow.next;
}
}
//If I use the following line firHalf list is empty when in the caller of this method (it's not in this method, however). Don't understand why ):
//firHalf = list;
firHalf.setRoot(list.getRoot());
secHalf.setRoot(slow.next);
slow.next = null;
}
}
private LinkedList<E> merge(LinkedList<E> a, LinkedList<E> b)
{
LinkedList<E> mergedList = new LinkedList<E>();
Node<E> dummy = new Node<E>(null);
Node<E> tail = dummy;
while(true)
{
if(a.getRoot() == null){
tail.next = b.getRoot();
break;
}
else if(b.getRoot() == null){
tail.next = a.getRoot();
break;
}
else
{
if(a.getRoot().data.compareTo(b.getRoot().data) <= 0)
{
tail.next = a.getRoot();
tail = tail.next;
a.setRoot(a.getRoot().next);
}
else
{
tail.next = b.getRoot();
tail = tail.next;
b.setRoot(b.getRoot().next);
}
tail.next = null;
}
}
mergedList.setRoot(dummy.next);
return mergedList;
}
public void mergeSort(LinkedList<E> list)
{
Node<E> root = list.getRoot();
LinkedList<E> left = new LinkedList<E>();
LinkedList<E> right = new LinkedList<E>();
if(root == null || root.next == null) return; //base case
split(list, left, right); //split
mergeSort(left);
mergeSort(right);
list = merge(left, right); // when this mergeSort returns this list should be
// referenced by the left or right variable of the
// current mergeSort call (but it isn't!)
}
}
I am fairly new to Java (coming from a C background) so I am sincerely sorry in advance if my code is utterly false. When I test the split and merge methods in the MergeSorter class independently, everything seems to work (splitting a list consisting of 0 or 1 element is not working and is driving me crazy but this is not needed for merge-sorting). The mergeSort method, however, is not working and I can't seem to figure out way. I tried to debug it myself and there's seems to be a problem when two halves are merged into one list and then the recursion returns. The newly merged list should be referenced by either the left or right variable of the current mergeSort call but instead I get only the last element instead of the whole list.
Method arguments in Java are always passed by value.
This can be a bit confusing, since objects are always accessed via references, so you might think they're passed by reference; but they're not. Rather, the references are passed by value.
What this means is, a method like this:
public void methodThatDoesNothing(Object dst, Object src) {
src = dst;
}
actually does nothing. It modifies its local variable src to refer to the same object as the local variable dst, but those are just local variables that disappear when the function returns. They're completely separate from whatever variables or expressions were passed into the method.
So, in your code, this:
firHalf = list;
does not really do anything. I guess what you want is:
while (! firHalf.isEmpty()) {
firHalf.deleteBeg();
}
if (! list.isEmpty()) {
firHalf.addBeg(list.root().data);
}
which modifies the objected referred to by firHalf so it has the same zero-or-one elements as list.
What's the best way to implement a stack using linked lists in Java?
EDIT: I would define best as most efficient using clean code. I have already used an array to implement a stack, but am not familiar with link lists so was wondering if anyone could help me implement something similar to below:
public class StackArray{
private Object [] objArray;
private int stackSize;
public StackArray(){
objArray = new Object[50];
stackSize = 0;
}
public StackArray(int size){
objArray = new Object[size];
stackSize = 0;
}
//public interface methods - push, pop, top, empty & clear
public void push(Object o)throws StackArrayException{
if(stackSize < objArray.length){
objArray[stackSize] = o;
stackSize ++;
}else{
throw new StackArrayException("Stack Overflow");
}
}
public Object pop()throws StackArrayException{
if(stackSize != 0){
stackSize--;
return(objArray[stackSize]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public void top() throws StackArrayException{
if(stackSize != 0){
return(objArray[stackSize-1]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public boolean empty(){
return (stackSize == 0):
}
public void clear(){
stackSize = 0;
}
}
EDIT: Here is the linked list implementation if anyone is interested..
public class StackList{
private Node listHead;
protected class Node{
protected Object datum;
protected Node next;
public Node(Object o, Node n){
datum = o;
next = n;
}
public StackList(){
listHead = null;
}
//public interface methods - push pop top empty clear
public void push(Object o){
listHead = new Node(o, listHead);
}
public Object pop() throws StackListException{
if(listHead!=null){
Object top = listHead.datum;
listHead = listHead.next;
return top;
}else{
throw new StackListException("Stack Underflow");
}
}
public Object top()throws StackListException{
if(listHead != null){
return(listHead.datum);
}else{
throw new StackListException("Stack Underflow");
}
}
public boolean empty(){
return (listHead == null);
}
public void clear(){
listHead = null;
}
}
Assuming you genuinely want to do this from scratch rather than using one of the perfectly good existing stack implementations then I would recommend:
Create a "MyStack< T >" class which implements any interfaces you want (perhaps List < T >?)
Within MyStack create a "private static final class Node< T >" inner class for each linked list item. Each node contains a reference to an object of type T and a reference to a "next" Node.
Add a "topOfStack" Node reference to MyStack.
The push and pop operations just need to operate on this topOfStack Node. If it is null, the Stack is empty. I'd suggest using the same method signatures and semantics as the standard Java stack, to avoid later confusion.....
Finally implement any other methods you need. For bonus points, implement "Iterable< T >" in such a way that it remembers the immutable state of the stack at the moment the iterator is created without any extra storage allocations (this is possible :-) )
Why don't you just use the Stack implementation already there?
Or better (because it really a linked list, its fast, and its thread safe): LinkedBlockingDeque
If you're talking about a single linked list (a node has a reference to the next object, but not the previous one), then the class would look something like this :
public class LinkedListStack {
private LinkedListNode first = null;
private LinkedListNode last = null;
private int length = 0;
public LinkedListStack() {}
public LinkedListStack(LinkedListNode firstAndOnlyNode) {
this.first = firstAndOnlyNode;
this.last = firstAndOnlyNode;
this.length++;
}
public int getLength() {
return this.length;
}
public void addFirst(LinkedListNode aNode) {
aNode.setNext(this.first);
this.first = aNode;
}
}
public class LinkedListNode {
private Object content = null;
private LinkedListNote next = null;
public LinkedListNode(Object content) {
this.content = content;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
public LinkedListNode getNext() {
return this.next;
}
public void setContent(Object content) {
this.content = content;
}
public Object getContent() {
return this.content;
}
}
Of course you will need to code the rest of the methods for it to work properly and effectively, but you've got the basics.
Hope this helps!
For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
StackLinkedList‘s push method internally calls linkedList’s insertFirst() method
public void push(int value){
linkedList.insertFirst(value);
}
StackLinkedList’s method internally calls linkedList’s deleteFirst() method
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
Full Program
/**
*Exception to indicate that LinkedList is empty.
*/
class LinkedListEmptyException extends RuntimeException{
public LinkedListEmptyException(){
super();
}
public LinkedListEmptyException(String message){
super(message);
}
}
/**
*Exception to indicate that Stack is empty.
*/
class StackEmptyException extends RuntimeException {
public StackEmptyException(){
super();
}
public StackEmptyException(String message){
super(message);
}
}
/**
*Node class, which holds data and contains next which points to next Node.
*/
class Node {
public int data; // data in Node.
public Node next; // points to next Node in list.
/**
* Constructor
*/
public Node(int data){
this.data = data;
}
/**
* Display Node's data
*/
public void displayNode() {
System.out.print( data + " ");
}
}
/**
* LinkedList class
*/
class LinkedList {
private Node first; // ref to first link on list
/**
* LinkedList constructor
*/
public LinkedList(){
first = null;
}
/**
* Insert New Node at first position
*/
public void insertFirst(int data) {
Node newNode = new Node(data); //Creation of New Node.
newNode.next = first; //newLink ---> old first
first = newNode; //first ---> newNode
}
/**
* Deletes first Node
*/
public Node deleteFirst()
{
if(first==null){ //means LinkedList in empty, throw exception.
throw new LinkedListEmptyException("LinkedList doesn't contain any Nodes.");
}
Node tempNode = first; // save reference to first Node in tempNode- so that we could return saved reference.
first = first.next; // delete first Node (make first point to second node)
return tempNode; // return tempNode (i.e. deleted Node)
}
/**
* Display LinkedList
*/
public void displayLinkedList() {
Node tempDisplay = first; // start at the beginning of linkedList
while (tempDisplay != null){ // Executes until we don't find end of list.
tempDisplay.displayNode();
tempDisplay = tempDisplay.next; // move to next Node
}
System.out.println();
}
}
/**
* For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
*/
class StackLinkedList{
LinkedList linkedList = new LinkedList(); // creation of Linked List
/**
* Push items in stack, it will put items on top of Stack.
*/
public void push(int value){
linkedList.insertFirst(value);
}
/**
* Pop items in stack, it will remove items from top of Stack.
*/
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
/**
* Display stack.
*/
public void displayStack() {
System.out.print("Displaying Stack > Top to Bottom : ");
linkedList.displayLinkedList();
}
}
/**
* Main class - To test LinkedList.
*/
public class StackLinkedListApp {
public static void main(String[] args) {
StackLinkedList stackLinkedList=new StackLinkedList();
stackLinkedList.push(39); //push node.
stackLinkedList.push(71); //push node.
stackLinkedList.push(11); //push node.
stackLinkedList.push(76); //push node.
stackLinkedList.displayStack(); // display LinkedList
stackLinkedList.pop(); //pop Node
stackLinkedList.pop(); //pop Node
stackLinkedList.displayStack(); //Again display LinkedList
}
}
OUTPUT
Displaying Stack > Top to Bottom : 76 11 71 39
Displaying Stack > Top to Bottom : 71 39
Courtesy : http://www.javamadesoeasy.com/2015/02/implement-stack-using-linked-list.html
Use the STL adapter std::stack. Why? Because the code you don't have to write is the fastest way to completion of your task. stack is well-tested, and likely to not need any attention from you. Why not? Because there are some special-purpose requirements needed by your code, undocumented here.
By default stack uses a deque double-ended queue, but it merely requires the underlying container to support "Back Insertion Sequence", also known as .push_back.
typedef std::stack< myType, std::list<myType> > myStackOfTypes;
Here is a tutorial implement using an array and linked list stack implementation.
It depends on the situation.
Array :- you can not resize it (fix size)
LinkedList :- it takes more memory than the array-based one because it wants to keep next node in memory.
I saw many stack implementation using LinkedList, At the end I understand what stack is.. and implemented stack by myself(for me it's clean and efficient). I hope you welcome new implementations. Here the code follows.
class Node
{
int data;
Node top;
public Node()
{
}
private Node(int data, Node top)
{
this.data = data;
this.top = top;
}
public boolean isEmpty()
{
return (top == null);
}
public boolean push(int data)
{
top = new Node(data, top);
return true;
}
public int pop()
{
if (top == null)
{
System.out.print("Stack underflow<-->");
return -1;
}
int e = top.data;
top = top.top;
return e;
}
}
And here the main class for it.
public class StackLinkedList
{
public static void main(String[] args)
{
Node stack = new Node();
System.out.println(stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
}
}