0% found this document useful (0 votes)
4 views31 pages

Data structure lab program

The document provides implementations of various data structures and algorithms in Java, including stacks and queues using both arrays and linked lists, infix to postfix conversion, binary tree traversals, linear and binary search algorithms, and depth-first search in graphs. Each section includes code examples and outputs demonstrating the functionality of the implemented structures and algorithms. It serves as a comprehensive guide for understanding fundamental data structures and their operations.

Uploaded by

nazvivo2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views31 pages

Data structure lab program

The document provides implementations of various data structures and algorithms in Java, including stacks and queues using both arrays and linked lists, infix to postfix conversion, binary tree traversals, linear and binary search algorithms, and depth-first search in graphs. Each section includes code examples and outputs demonstrating the functionality of the implemented structures and algorithms. It serves as a comprehensive guide for understanding fundamental data structures and their operations.

Uploaded by

nazvivo2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

ARRAY IMPLEMENTATION OF STACKS


class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}
void print(){
for(int i = top;i>-1;i--){
System.out.print(" "+ a[i]);
}
}
}

class StackArray {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(" STACK USING ARRAYS\n\n");
System.out.println(s.pop() + " Popped from stack");
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}
OUTPUT
STACK USING ARRAYS

10 pushed into stack


20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is : 20
Elements present in stack : 20 10
2. QUEUE USING AN ARRAY

class Queue {
static private int front, rear, capacity;
static private int queue[];

Queue(int c)
{
front = rear = 0;
capacity = c;
queue = new int[capacity];
}

static void queueEnqueue(int data)


{
if (capacity == rear) {
System.out.printf("\nQueue is full\n");
return;
}
else {
queue[rear] = data;
rear++;
}
return;
}
static void queueDequeue()
{
if (front == rear) {
System.out.printf("\nQueue is empty\n");
return;
}
else {
int element = queue[front];
if (front >= rear) {
front = -1;
rear = -1;
}
else {
front++;
}
System.out.println(element + " Deleted");
return;
}
}
static void queueDisplay()
{
int i;
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i],"\n");
}
return;
}
static void queueFront()
{
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
System.out.printf("\nFront Element is: %d", queue[front]);
return;
}
}

class StaticQueueinjava {
public static void main(String[] args)
{
Queue q = new Queue(4);
System.out.printf("\n QUEUE USING ARRAYS \ n\n");
q.queueDisplay();
q.queueEnqueue(20);
q.queueEnqueue(30);
q.queueEnqueue(40);
q.queueEnqueue(50);
q.queueDisplay();

q.queueEnqueue(60);
q.queueDisplay();

q.queueDequeue();
q.queueDequeue();
System.out.printf("\n\nafter two node deletion\n\n");
q.queueDisplay();
q.queueFront();
}
}
OUTPUT

QUEUE USING ARRAYS

Queue is Empty
20 <-- 30 <-- 40 <-- 50 <--
Queue is full
20 <-- 30 <-- 40 <-- 50 <--
20 deleted
30 deleted
after two node deletion

40 <-- 50 <--
Front Element is: 40
3. STACK USING SINGLY LINKED LIST
import static java.lang.System.exit;
class StackLink {
public static void main(String[] args)
{
StackUsingLinkedlist obj= new StackUsingLinkedlist();
obj.push(11);
obj.push(22);
obj.push(33);
obj.push(44);
System.out.printf("STACK USING LINKED LIST");

obj.display();

System.out.printf("\nTop element is %d\n",obj.peek());

obj.pop();
obj.pop();

obj.display();

System.out.printf("\nTop element is %d\n",obj.peek());


}
}

// Create Stack Using Linked list


class StackUsingLinkedlist {

private class Node {

int data; // integer data


Node link; // reference variable Node type
}

Node top;

StackUsingLinkedlist() { this.top = null; }

public void push(int x) // insert at the beginning


{
Node temp = new Node();

if (temp == null) {
System.out.print("\nHeap Overflow");
return;
}

temp.data = x;

temp.link = top;
top = temp;
}

public boolean isEmpty() { return top == null; }

public int peek()


{
if (!isEmpty()) {
return top.data;
}
else {
System.out.println("Stack is empty");
return -1;
}
}

public void pop() // remove at the beginning


{
if (top == null) {
System.out.print("\nStack Underflow");
return;
}
System.out.println("Element Popped is " + top.data);
top = (top).link;
}

public void display()


{
if (top == null) {
System.out.printf("\nStack Underflow");
exit(1);
}
else {
Node temp = top;
while (temp != null) {

// print node data


System.out.print(temp.data);

// assign temp link to temp


temp = temp.link;
if(temp != null)
System.out.print(" -> ");
}
}
}
}
OUTPUT
STACK USING LINKED LIST
44 -> 33 -> 22 -> 11
Top element is 44
Element popped is 44
Element popped is 33
22 -> 11
Top element is 22
4. QUEUE USING LINKED LIST

class Node {
int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

class Queue {
Node front, rear;
int length;

public Queue() {
this.front = this.rear = null;
this.length=0;
}

void enqueue(int key) {


this.length++;
Node temp = new Node(key);

if (this.rear == null) {
this.front = this.rear = temp;
return;
}

this.rear.next = temp;
this.rear = temp;
}

void deque() {
if (this.front == null)
return;

Node temp = this.front;


this.front = this.front.next;

if (this.front == null)
this.rear = null;

temp.next = null;
}

int peek() {
if (this.front != null)
return this.front.data;
return Integer.MIN_VALUE;
}

int size(){
return this.length;
}

void printQueue(){
Node temp=this.front;
System.out.print("Element of Queue : ");
while(temp!=null){
System.out.print(temp.data+" ");
temp=temp.next;
}
System.out.println();
}
}

public class QueueList {


public static void main(String[] args) {
Queue q = new Queue();
System.out.println("\nQUEUE USING LINKED LIST\n\n");
q.enqueue(10);
q.enqueue(20);

q.printQueue();
System.out.println("Size :" + q.size());
q.deque();
q.deque();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.printQueue();
System.out.println("Size :" + q.size());
System.out.println("Front item is: " + q.peek());
}
}
OUTPUT

QUEUE USING LINKED LIST


Element of Queue : 10 20
Size :2
Element of Queue : 30 40 50
Size :5
Front item is: 30
5. INFIX TO POSTFIX CONVERSION
import java.util.Stack;

public class InfixToPostfix {

// Function to return precedence of operators


static int prec(char c) {
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}

static char associativity(char c) {


if (c == '^')
return 'R';
return 'L'; // Default to left-associative
}

static void infixToPostfix(String s) {


StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();

for (int i = 0; i < s.length(); i++) {


char c = s.charAt(i);

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
result.append(c);
}
else if (c == '(') {
stack.push(c);
}
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
stack.pop(); // Pop '('
}
else {
while (!stack.isEmpty() && (prec(s.charAt(i)) < prec(stack.peek()) ||
prec(s.charAt(i)) == prec(stack.peek()) &&
associativity(s.charAt(i)) == 'L')) {
result.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}

System.out.println(result);
}

public static void main(String[] args) {


String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println("INFIX TO POSTFIX CONVERSION\n\n");
// Function call
infixToPostfix(exp);
}
}
OUTPUT

INFIX TO POSTFIX CONVERSION

abcd^e-fgh*+^*+i-
6. BINARY TREE TRAVERSAL(INORDER,PREORDER,POSTORDER)
import java.io.*;

class Node {

int data;
Node left;
Node right;
Node(int v)
{
this.data = v;
this.left = this.right = null;
}
}

class BTT{
// Inorder Traversal
public static void printInorder(Node node)
{
if (node == null)
return;

// Traverse left subtree


printInorder(node.left);

// Visit node
System.out.print(node.data + " ");

// Traverse right subtree


printInorder(node.right);
}
public static void printPreorder(Node node)
{
if (node == null)
return;

// Visit node
System.out.print(node.data + " ");

// Traverse left subtree


printPreorder(node.left);

// Traverse right subtree


printPreorder(node.right);
}
public static void printPostorder(Node node)
{
if (node == null)
return;
// Traverse left subtree
printPostorder(node.left);

// Traverse right subtree


printPostorder(node.right);

// Visit node
System.out.print(node.data + " ");
}

public static void main(String[] args)


{
// Build the tree
Node root = new Node(100);
root.left = new Node(20);
root.right = new Node(200);
root.left.left = new Node(10);
root.left.right = new Node(30);
root.right.left = new Node(150);
root.right.right = new Node(300);

// Function call
System.out.print("Inorder Traversal: ");
printInorder(root);
System.out.print("\nPreorder Traversal: ");
printPreorder(root);
System.out.print("\nPostorder Traversal: ");
printPostorder(root);

}
}
OUTPUT

Inorder Traversal: 10 20 30 100 150 200 300


Preorder Traversal: 100 20 10 30 200 150 300
Postorder Traversal: 20 10 30 200 150 300 100
7. LINEAR SEARCH

public class LinearSearchExample{


public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println("LINEAR SEARCH\n\n");
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

OUTPUT

LINEAR SEARCH

50 is found at index: 3
7. BINARY SEARCH

class BinarySearch {
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == x)
{
return mid;
} else if (arr[mid] > x)
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return -1;
}

public static void main(String args[])


{
BinarySearch ob = new BinarySearch();

int arr[] = { 2, 3, 4, 10, 40 };


int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
System.out.println("BINARY SEARCH\n\n");
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "+ result);
}
}

OUTPUT

BINARY SEARCH

Element found at index 3


8. DEPTH FIRST SEARCH IN GRAPH
import java.util.*;
public class DFS_Graph
{
final int TRUE=1;
final int FALSE=0;
final int MAX=20;
int [][]G=new int[MAX][MAX];
int []visit=new int[MAX];
int []q=new int[MAX];
int n,v1,v2;
int front,rear;
DFS_Graph()
{
System.out.print("Enter number of nodes");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for (int i=1;i<=n;i++)
visit[i]=FALSE;
for(v1=1;v1<=n;v1++)
{
for(v2=1;v2<=n;v2++)
G[v1][v2]=FALSE;
}
front=rear=-1;
}
void createGraph()
{
char ans;
System.out.println("Enter the edger with vertex no. starting from 1");
do
{
System.out.println("Enter the vertices v1&v2:");
Scanner obj=new Scanner(System.in);
v1=obj.nextInt();
v2=obj.nextInt();
if(v1>n || v2>n)
System.out.println("Invalid Vertex Number");
else
{
G[v1][v2]=TRUE;
G[v2][v1]=TRUE;
}
System.out.println("Want to add more edges (y\n)?");
ans=obj.next().charAt(0);
}
while((ans=='y')||(ans=='Y'));
}
void matrix()
{
System.out.println("Adjacency Matrix for the graph is");
for(int v1=1;v1<=n;v1++)
{
for(int v2=1;v2<=n;v2++)
System.out.print(G[v1][v2]+" ");
System.out.println();
}
}
void dfs(int v)
{
int i;
System.out.println(v+" ");
visit[v]=TRUE;
for(i=1;i<=n;i++)
{
if(G[v][i]==TRUE && visit[i]==FALSE)
dfs(i);
}
}
public static void main(String[] args)
{
System.out.println("Program to create a Graph and traverse in DFS manner");
DFS_Graph g=new DFS_Graph();
g.createGraph();
g.matrix();
System.out.println("Depth first traversal for the above graph is");
g.dfs(1);
}
}
OUTPUT:
Program to create a Graph and traverse in DFS manner
Enter number of nodes 4
Enter the edges with vertex no. starting from 1
Enter the vertices v1&v2:
1
2
Want to add more edges(y/n)?
Y
Enter the vertices v1&v2:
1
4
Want to add more edges(y/n)?
Y
Enter the vertices v1&v2:
3
4
Want to add more edges(y/n)?
Y
Enter the vertices v1&v2:
1
3
Want to add more edges(y/n)?
N
Adjacency Matrix for the graph is
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
Depth first traversal for the above graph is 1 2 3 4
8. BREADTH FIRST SEARCH_IN GRAPH
public class BFS_Graph
{
final int TRUE=1;
final int FALSE=0;
final int MAX=20;
int [][]G=new int[MAX][MAX];
int []visit=new int[MAX];
int []q=new int[MAX];
int n,v1,v2;
int front,rear;
BFS_Graph()
{
System.out.print("Enter number of nodes");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for (int i=1;i<=n;i++)
visit[i]=FALSE;
for(v1=1;v1<=n;v1++)
{
for(v2=1;v2<=n;v2++)
G[v1][v2]=FALSE;
}
front=rear=-1;
}
void createGraph()
{
char ans;
System.out.println("Enter the edger with vertex no. starting from 1");
do
{
System.out.println("Enter the vertices v1&v2:");
Scanner obj=new Scanner(System.in);
v1=obj.nextInt();
v2=obj.nextInt();
if(v1>n || v2>n)
System.out.println("Invalid Vertex Number");
else
{
G[v1][v2]=TRUE;
G[v2][v1]=TRUE;
}
System.out.println("Want to add more edges (y/n)?");
ans=obj.next().charAt(0);
}
while((ans=='y')||(ans=='Y'));
}
void matrix()
{
System.out.println("Adjacency Matrix for the graph is");
for(int v1=1;v1<=n;v1++)
{
for(int v2=1;v2<=n;v2++)
System.out.print(G[v1][v2]+" ");
System.out.println();
}
}
void bfs(int v)
{
int i;
System.out.println(v+" ");
visit[v]=TRUE;
q[++rear]=v;
while(front!=rear)
{
v=q[++front];
System.out.println(v+" ");
for(i=1;i<=n;i++)
{
if(G[v][i]==TRUE && visit[i]==FALSE)
{
q[++rear]=i;
visit[i]=TRUE;
}
}
}
}
public static void main(String[] args)
{
System.out.println("Program to create a Graph and traverse in BFS manner");
BFS_Graph g=new BFS_Graph();
g.createGraph();
g.matrix();
System.out.println("Breadth first traversal for the above graph is");
g.bfs(1);
}
}
OUTPUT:

Program to create a Graph and traverse in BFS


mannerEnter number of nodes 4
Enter the edges with vertex no. starting
from 1Enter the vertices v1&v2:
1
2
Want to add more
edges(y/n)?Y
Enter the vertices v1&v2:
1
3
Want to add more
edges(y/n)?Y
Enter the vertices v1&v2:
1
4
Want to add more
edges(y/n)?Y
Enter the vertices v1&v2:
2
3
Want to add more
edges(y/n)?N
Adjacency Matrix for the graph is
0 1 1 1
1 0 1 0
1 1 0 0
1 0 0 0
Breadth first traversal for the above graph is 1 1 2 3 4
9. SINGLE SOURCE SHORTEST PATH

import java.io.*;
import java.lang.*;
import java.util.*;

class ShortestPath {
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{

int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}

return min_index;
}

void printSolution(int dist[])


{
System.out.println("Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " + dist[i]);
}

void dijkstra(int graph[][], int src)


{
int dist[] = new int[V]; // The output array.
// dist[i] will hold

Boolean sptSet[] = new Boolean[V];

for (int i = 0; i < V; i++) {


dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

dist[src] = 0;

for (int count = 0; count < V - 1; count++) {

int u = minDistance(dist, sptSet);

sptSet[u] = true;
for (int v = 0; v < V; v++)

if (!sptSet[v] && graph[u][v] != 0


&& dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist);
}

public static void main(String[] args)


{

int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },


{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
ShortestPath t = new ShortestPath();

// Function call
t.dijkstra(graph, 0);
}
}
OUTPUT

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

You might also like