Friday, July 3, 2015

Stack Implementation as Array , Dynamic Array and LinkedList

Stack implementation as Array:

package ds.stack.implementation;

class StackArray {

static int stackSize = 3;

int[] stackArray = new int[stackSize];

int index = -1;

void add(int sData) {
if (index < stackSize - 1) {
stackArray[++index] = sData;
} else {
System.out.println(" Stack OverFlow");
}
}

void remove() {
if (index >= 0)
index--;
else
System.out.println(" Stack UnderFlow");

}

void display() {
for (int n = 0; n < index; n++)
System.out.print(" " + stackArray[n]);
}

}

public class StackAsArrayImpl {
public static void main(String args[]) {
StackArray stackArray = new StackArray();
stackArray.add(11);
stackArray.add(12);
stackArray.add(13);
stackArray.display();
stackArray.remove();
System.out.println("  -------------------------------------- ");
stackArray.display();
}
}


Stack Implementation as LinkedList:


package ds.stack.implementation;

class StackList {
Node first = null;

public StackList(Node first) {
this.first = first;
}

StackList() {

}

void push(int sData) {
Node newNode = new Node(sData);
if (first == null)
first = newNode;
else {
Node current = first;
while (current.next != null) {
current = current.next;
// newNode.next = null;
}
current.next = newNode;
newNode.next = null;
}
}

void pop() {
if (first == null)
return;
else {
Node current = first.next;
while (current.next.next != null) {
current = current.next;
}
current.next = null;
}
}

void display(Node node) {
Node current = node;
do {
System.out.print(" " + current.nData);
current = current.next;
} while (current != null);
}
}

class Node {
int nData;
Node next;

Node(int nData) {
this.nData = nData;
}

Node() {
}
}

public class StackAsListSample {
public static void main(String args[]) {
StackList stackList = new StackList();

stackList.push(12);
stackList.push(13);
stackList.push(14);
stackList.push(15);
stackList.push(16);

stackList.display(stackList.first);

stackList.pop();
System.out.println();
System.out.println(" -------------------------- ");

stackList.display(stackList.first);

}

}


No comments:

Post a Comment