Tuesday, May 10, 2011

List Implementation of Stacks(C#, Java, C++, C)

Here is my List implementation of stack(Sample Code).
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C#
//StackADTList.cs
using System;
using System.Collections.Generic;

namespace StackUsingLists
{
public class StackADTList
{
int _top = -1;
List<int> listStack = null;

//We can implement automatically growable Stack as well normal size restricted stack also
//Here we will see limited and size restricted stack.
public StackADTList(int nCapacity)
{
listStack = new List<int>(nCapacity);
_top = -1;
}

public int Top
{
get{ return _top;}
}

public int StackSize
{
get{return listStack.Capacity;}
}

public void push(int item)
{
if ((_top + 1) == StackSize)
throw new Exception("Stack Overflow");
_top = _top + 1;
listStack.Add(item);
}

public int pop()
{
if (_top < 0)
throw new Exception("Stack Underflow");
int item = listStack[_top];
listStack.RemoveAt(_top);
_top = _top - 1;
return item;
}

public bool isFull()
{
if ((_top + 1) == StackSize)
return true;
else
return false;
}

public bool isEmpty()
{
if (_top < 0)
return true;
else
return false;
}

public override string ToString()
{
string strItems = "Stack : ";
if (isEmpty())
{
strItems += "empty";
}
else
{
foreach(int item in listStack)
{
strItems += item + " ";
}
}
return strItems;
}
}
}

//Program.cs
using System;
namespace StackUsingLists
{
class Program
{
static void Main(string[] args)
{
try
{
StackADTList objListStack = new StackADTList(10);

objListStack.push(10);
objListStack.push(25);
objListStack.push(50);
Console.WriteLine(" " + objListStack.ToString());
objListStack.pop();
objListStack.pop();
objListStack.pop();
Console.WriteLine(" " + objListStack.ToString());
objListStack.pop();
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp.Message);
}
Console.Read();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Java

Note: Sorry for formatting, i will try to update as it is looks like in my IDE

package stacksadtlist;
import java.util.LinkedList;
class StacksADT
{
int _top;
int _size;
LinkedList objList = null;
public StacksADT(int nSize)
{
_size = nSize;
_top = -1;
objList = new LinkedList();
}
public int Size()
{
return objList.size();
}
public int TopIndex()
{
return _top;
}
public void push(int item) throws Exception
{
if((_top + 1) == _size)
{
throw new Exception("Stack Overlow");
}
_top = _top + 1;
objList.add((Integer)item);
}
public int pop() throws Exception
{
if(_top < 0)
{
throw new Exception("Stack Underflow");
}
int tmpItem = objList.remove(_top);
_top = _top - 1;
return tmpItem;
}
public boolean isFull()
{
if((_top + 1) == Size())
return true;
else
return false;
}
public boolean isEmpty()
{
if(_top < 0)
return true;
else
return false;
}

@ Override
public String toString()
{
String strItems = "Stack : ";
if (isEmpty())
{
strItems += "Empty";
} else {
for (int i = 0; i <= _top; i++) {
strItems += objList.get(i) + " ";
}
}
return strItems;
}
}

public class StacksADTList
{
public static void main(String[] args)
{
try
{
StacksADT objStack =new StacksADT(10);
objStack.push(10);
objStack.push(25);
objStack.push(50);
System.out.println(objStack.toString());

objStack.pop();
objStack.pop();
objStack.pop();
System.out.println(objStack.toString());

objStack.pop();

}
catch(Exception exp)
{
System.out.println("" + exp.getMessage());
}
try
{
System.in.read();
}
catch(Exception exp1)
{
//DOn't do anything
}
}
}


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C++

I will update very soon
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *nextNode;
}*head, *current, *tmp;

int top;
int stacksize = 10;
int data;

void push(int);
int pop();
int isFull();
int isEmpty();
void printStack();

int main(int argc, char *argv[])
{
int exitCondition = -1;
int data;
top = -1;
//initializing Head
head = malloc(sizeof(struct node));
if( head == NULL)
{
printf("Memory Error");
return;
}
head->data = -999;
head->nextNode = NULL;
current = head;
//Temporary node for traversing through the list
tmp = malloc(sizeof(struct node));
if( tmp == NULL)
{
printf("Memory Error");
return;
}
tmp = head;

//Stack Menu
do
{
printf("\nSelect an Operation \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Is Stack Empty\n");
printf("4. is Stack Full\n");
printf("5. Print Stack\n");
printf("6. Exit\n");
scanf("%d",&exitCondition);

switch(exitCondition)
{
case 1:
printf("Enter a number to push into the stack \n");
scanf("%d", &data);
push(data);
printStack();
break;
case 2:
data = pop();
if(data == head->data)
{
printf("Stack :Underflow");
}
else
{
printf(" %d reomved from the stack\n", data);
printStack();
}
break;
case 3:
data = isEmpty();
if(data == 1)
{
printf(" Stack : Empty\n", data);
}
break;
case 4:
data = isFull();
if(data == 1)
{
printf(" Stack : Full\n", data);
}
break;
case 5:
printStack();
break;
case 6:
break;
default:
printf("Please enter a valid option. \n");
system("EXIT");
}
}
while(exitCondition != 6);
system("PAUSE");
return 0;
}

void push(int item)
{
//Creating the new node in the list - start
struct node *newNode;
newNode = malloc(sizeof(struct node));
if( newNode == NULL)
{
printf("Memory Error");
return;
}
newNode->data = item;
newNode->nextNode = NULL;
//Creating the new node in the list - end

if((top + 1) == stacksize)
printf("Stack : Overflow \n");
top = top + 1;
if( current != NULL)
{
current->nextNode = newNode;
current = newNode;
}
}

int pop()
{
if(top < 0)
{
data = head->data;
}
else
{
top = top - 1;
data = current->data;
//here we need to do some extra coding for removing the lst node in the list
tmp = head;
while(tmp->nextNode != NULL)
{
if(tmp->nextNode == current)
{
current = tmp;
current->nextNode = NULL;
break;
}
tmp = tmp->nextNode;
}
tmp = head;
}
return data;
}
int isFull()
{
if((top+1) == stacksize)
return 1;
else
return 0;
}
int isEmpty()
{
if(top < 0)
return 1;
else
return 0;
}
void printStack()
{
printf("Stack :");
if(top < 0 )
{
printf(" Empty");
}
else
{
tmp = head;
do
{
tmp = tmp->nextNode;
if(tmp!=NULL)
{
printf ("%d ", tmp->data);
}
}
while(tmp->nextNode != NULL);
}
printf("\n");
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


Monday, May 9, 2011

Array Implementation of Stacks(C#, Java, C++, C)

Here is my Array Implementation of stack(Sample Code)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C#
//StackADT.cs
using System;
namespace Stacks
{
public class StackADT
{
//Array for storing stack elements
private int[] items = null;
//Stack size
private int _size = 0;
//Top index
private int _top = -1;
//Read only property, because to stop modifying the size of the stack during the operation
public int Size
{
get {return _size;}
}

//Standard Stack Operations - start
//Constructor - for creating and initializing the stack
public StackADT(int nSize)
{
this._size = nSize;
items =
new int[_size];
}
//Getting the index of top element
public int Top
{
get {return this._top;}
}
//For inserting elements in to Stack
public void push(int item)
{
if (_top == (_size - 1))
throw new Exception("Stack Overflow");
items[++_top] = item;
}
//For deleting elements in to Stack
public int pop()
{
if (_top < 0)
throw new Exception("Stack Underflow");
return items[_top--];
}
public bool isFull()
{
if (_top == (_size - 1))
return true;
return false;
}
public bool isEmpty()
{
if (_top < 0)
return true;
return false;
}
//Stack Operations - end

//Just for printing the Stack
public override string ToString()
{
String strItems = "";
if (isEmpty())
{
strItems =
"Stack Empty";
}
else
{
for (int i = 0; i <= _top; i++)
{
strItems += items[i] +
" ";
}
}
Console.WriteLine("" + strItems);
return strItems;
}
}
}
//Program.cs
using System;
namespace Stacks
{
class Program
{
static void Main(string[] args)
{
StackADT objStack = new StackADT(10);
try
{
objStack.push(10);
objStack.push(25);
objStack.push(50);
objStack.ToString();
objStack.pop();
objStack.pop();
objStack.ToString();
objStack.pop();
objStack.ToString();
objStack.pop();
objStack.Restring();
}
catch (Exception exp)
{
Console.WriteLine("" + exp.Message);
}
Console.ReadLine();
}
}
}


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

C++
//StackADT.h
class StackADT
{
int _top;
int _size;
int* Items;
public:
StackADT(
int);
~StackADT(
void);
void push(int);
int pop();
int getTop();
bool isFull();
bool isEmpty();
void DisplayStack();
};
//StackADT.cpp
#include "StackADT.h"
#include <iostream>
#include <ios>
using namespace std;
StackADT::~StackADT(
void)
{
}
StackADT::StackADT(
int nSize)
{
Items =
new int[nSize];
_top = -1;
_size = nSize;
}
void StackADT::push(int item)
{
if((_top + 1) == _size)
{
cout <<
"Stack Overflow" << endl;
return;
}
_top = _top + 1;
Items[_top] = item;
}
int StackADT::pop()
{
if (_top < 0)
{
cout <<
"Stack Underflow" << endl;
return -1;
}
int item = Items[_top];
_top = _top - 1;
return item;
}
int StackADT::getTop()
{
return _top;
}
bool StackADT::isEmpty()
{
if (_top < 0)
return true;
return false;
}
bool StackADT::isFull()
{
if (_top == _size)
return true;
return false;
}
void StackADT::DisplayStack()
{
if(isEmpty())
{
cout <<
"Stack Empty" << endl;
}
else
{
for(int i=0;i<=_top;i++)
{
cout << Items[i] <<
" ";
}
}
cout << endl;
}
//Stacks.cpp
#include <iostream>
#include "StackADT.h"
using namespace std;

int main()
{
StackADT objStack(10);
objStack.push(10);
objStack.push(25);
objStack.push(50);
objStack.DisplayStack();
objStack.pop();
objStack.pop();
objStack.DisplayStack();
objStack.pop();
objStack.DisplayStack();
objStack.pop();
objStack.DisplayStack();
return 0;
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Java

//StackADT.java
package stacks;
public class StackADT
{
//Array for storing stack elements
private int[] items = null;
//Stack size
private int _size = 0;
//Top index
private int _top = -1;

//Read only property, because to stop modifying the size of the stack during the
//operation
public int getSize() {
return _size;
}
//Standard Stack Operations - start

//Constructor - for creating and initializing the stack
public StackADT(int nSize) {
this._size = nSize;
items =
new int[_size];
}

//Getting the index of top element
public int getTop() {
return this._top;
}

//For inserting elements in to Stack
public void push(int item) throws Exception {
if (_top == (_size - 1)) {
//System.out.println("Stack Overflow");
throw new Exception("Stack Overflow");
}
items[++_top] = item;
}

//For deleting elements in to Stack
public int pop() throws Exception {
if (_top < 0) {
//System.out.println("Stack Underflow");
throw new Exception("Stack Underflow");
}
return items[_top--];
}

public boolean isFull() {
if (_top == _size) {
return true;
}
return false;
}

public boolean isEmpty() {
if (_top < 0) {
return true;
}
return false;
}
//Stack Operations - end

//Just for printing the Stack
@ Override
public String toString() {
String strItems =
"";

if (isEmpty()) {
strItems =
"Stack Empty";
}
else {
for (int i = 0; i <= _top; i++) {
strItems += items[i] +
" ";
}
}
System.out.println(
"" + strItems);
return strItems;
}
}

//Stacks.java
package stacks;
public class Stacks
{
public static void main(String[] args)
{
StackADT objStack =
new StackADT(10);
try
{
objStack.push(10);
objStack.push(25);
objStack.push(50);
objStack.toString();

//50 will be removed
objStack.pop();
objStack.pop();
objStack.toString();
objStack.pop();
objStack.toString();
objStack.pop();
objStack.toString();
System.in.read();
}
catch(Exception exp)
{
System.out.println(
"" + exp.getMessage());
}

}
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

C
I will post the code in C very soon. I am getting some issues in installing C in my laptop.

#include <stdio.h>
#include <stdlib.h>
int top = -1;
int stacksize = 10;
int stack[10];
void push(int);
int pop();
void isFull();
void isEmpty();
void printStack();
int main(int argc, char *argv[])
{
int exitCondition = -1;
int data;
do
{
printf("\nSelect an Operation \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Is Stack Empty\n");
printf("4. is Stack Full\n");
printf("5. Print Stack\n");
printf("6. Exit\n");
scanf("%d",&exitCondition);

switch(exitCondition)
{
case 1:
printf("Enter a number to push into the stack \n");
scanf("%d", &data);
push(data);
printStack();
break;
case 2:
data = pop();
printStack();
break;
case 3:
isEmpty();
break;
case 4:
isFull();
break;
case 5:
printStack();
break;
case 6:
return 0;
default:
printf("Please enter a valid option. \n");
}
}
while(exitCondition != 6);

system("PAUSE");
return 0;
}
void push(int item)
{
if(top == stacksize)
printf("Stack Overflow");
top = top + 1;
stack[top] = item;
}
int pop()
{
int item;
if(top < 0 )
printf("Stack Underflow");
item = stack[top];
top = top - 1 ;
return item;
}
void isFull()
{
if(top == stacksize)
printf("Stack : Full");
}
void isEmpty()
{
if(top < 0)
printf("Stack : Empty");
}
void printStack()
{
int i=0;
printf(" Stack : ");
if(top < 0)
{
printf(" Empty ");
}
else
{
for( i= 0;i<=top;i++)
{
printf(" %d ",stack[i]);
}
}
printf("\n");
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Saturday, May 7, 2011

Stacks

Stack is data structure in which all the operations will be done on the top element. It is also called as LIFO(Last In, First Out) model, in which the element which is inserted last will be removed first. It's a kind of Linear Data Structure. At any point of time, Only top element is visible outside.

List of Operations allowed on a Stack
Create(S) - creates the stack S
Push(S, x) - for inserting elements in to Stack
Pop (S) - for deleting elements from stack
Top(S) - returns the top element of the stack
isEmpty(S) - used to check whether the stack is empty or not
isFull(S) - used to check whether the stack is full or not.

Note : isFull is a special method, used in array based implementations only.



We can implement Stack with Arrays as well as with Lists also. Before we look into Algorithms and implementation details, first we will see the advantages and disadvantages with Stacks.

+ Stacks are used to manage methods at run time (when a method is called, its parameters and local variables are pushed onto a stack; when the method returns, the values are popped from the stack).

+ Many parsing algorithms (used by compilers to determine whether a program is syntactically correct) involve the use of stacks.

+ stacks can be used to evaluate arithmetic expressions (e.g., by a simple calculator program)

+ Stacks also useful for some operations on graphs

+ Stacks are also used for reversing things. If you push something, say a String onto a Stack one character at a time, and then construct a String from the members popped off the Stack, then the String is reversed.

+ The advantage of an array implementation of stack is simplicity. The disadvantage is lack of expansion, i.e. the size of the stack is preset.

+ The advantage of a linked list implementation of stack is automatic expandability. The disadvantage is complexity, but the linked list is probably a better idea.

Now lets see how we can implement Stacks. As we know, there 2 ways of implementing Stacks. One is using Arrays and another one is using Lists. Both ways follows the same algorithm.

Stack Algorithms (These are my steps, what i have understood from the book)





These are 4 basic operations. Other operations are just for facilitating Stack to perform these operations. Just like CreateStack, DisplayStack etc.. methods. Whatever the implementation type the basic algorithms
are same. We know that each algorithm will have Time Complexity. From the above algorithms, we can say that the time complexity of Stack is O(1).

ADT (Abstract Data Types)

What is an abstract data type? An abstract data type (ADT) is a data type defined only in terms of the operations that may be performed on objects of the type. Users (programmers) are allowed to examine and manipulate objects using only these operations and they are unaware of how the objects are implemented in the programming language.

"An Abstract Data Type (ADT) is a data structure and a collection of functions or procedures which operate on the data structure. "

Data Type vs Abstract Data Type :
A Data Type is characterized by
- a set of values
- a data representation, which is common to all these values
- a set of operations, which can be applied uniformly to all these values.

where as an Abstract Data Type is characterized by
- a set of values
- a set of operations, which can be applied uniformly to all these values
- it won't give the external access to the data representation

Abstract Data Type (ADT) sim­pli­fies the task of spec­i­fy­ing an algo­rithm by abstracting the details of it. So, the end user no need to worry, how it is implemented.

In simple Java or C# terms, It's just a Class.

An introduction to Data Structures

Data Structure is one of the very popular buzz words we will be listening in the field of Computer Science. It is used every where, every program and almost every software system. Literally we can say, without a Data Structure we can't write a perfect and an efficient program.

What is a Data Structure?

There are so many definitions available, but i like this one "A data structure is a specialized format for organizing and storing data, so that it can be used efficiently". There are different types of data structures available.

Data Structures can be classified in to two types

  1. Primitive Data Structures
  2. Non Primitive Data Structures

The Data Structures that can be operated directly are called as Primitive Data Structures. Also called as simple data types. Integer, Float, Character are some examples of Primitive Data Structures. These data structures supports very basic operations like creation, deletion, selection and updation.

The data structures which are not primitive are called Non-Primitive Data Structures which means these are data structures that cannot be directly manipulated . For example, Complex number. It can't be expressed as a simple type. Because it will have both imaginary part and real part. Stacks, Queues, Linked lists, Trees are few more examples of non-primitive data structures.

Again this non primitive data types can be divided in to two types

  1. Linear Data Structures
  2. Non-Linear Data Structures

Linear Data Structures are those, in which sequential addition and updation is possible. In another way, Elements in the data structure will form a sequence or adjacent to each other or can be arranged in a straight line. In terms of memory allocation, Contiguous blocks of memory will be allocated. Stacks, Queues, Arrays, Lists are few examples of linear data structures.

Non-Linear Data Structures are those, if one element can be connected to more than two adjacent elements then it is known as non-linear data structure. It's exactly opposite to linear data structures. Trees and Graphs are the examples of Non-Linear data structures.

See here for a full list of data structures and it's types.

The major advantages of data structures are :

  • It gives different level of organizing data.
  • It tells how data can be stored and accessed in its elementary level

We have so many data structures giving different types of data organization. It's good. But how we can select a data structure that can fit into our requirements. Which factors affect the selection of a data structure? To answer these questions, first we should know when a program is said to be good? A program is said to be good,if it meets all our requirements, good speed and efficiency. How you will you achieve the speed and efficiency? To answer this question, first we should know, what is an algorithm? what is the relationship between a program, an algorithm and a Data Structure.

In simple terms,

Algorithm : Steps to solve a problem

Program : Used to implement the algorithm

Data Structure : Organization of data, so that the data can used efficiently by the program.

If we want our program to be good and efficient, the underlying Algorithm and Data Structure should be efficient.

The efficiency of an Algorithm and Data structure will be calculated in terms of Space(Memory) and time.This Time factor is also called as Time Complexity where as Space measure is called as Space Complexity. There are different types notations available to specify the efficiency of a Data Structure and an Algorithm. Those are Big-Oh notation, Small-Oh notation, Big-Omega notation, Small-Omega notation and Theta Notation.

Why we need to know, all these details? Because, Each operation on a data structure will have these efficiency measures(Time Complexity and Space Complexity) which will decide the efficiency of the data structure. in turn it will help us in choosing the data structure for our program.