Professional Documents
Culture Documents
Ds Programs BSC 4
Ds Programs BSC 4
Page
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
temp=ptr.next;
ptr.next=ptr.next.next;
temp=null;
}
void show()
{
System.out.println("\nList Elements:");
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
}
}
class SListTest
{
public static void main(String as[]) throws Exception
{
String con="";
int x,op,p,v;
LinkedList l1=new LinkedList();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add more?(y,n):");
con=br.readLine();
}while(con.equals("y"));
l1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(br.readLine());
System.out.println("Enter Value to insert:");
v= Integer.parseInt(br.readLine());
l1.insert(p,v);
}
if(op==2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(br.readLine());
l1.del(p);
}
l1.show();
}while(op<4);
}
3
Page
}
/* Output: */
Enter elements to create
30
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:
30 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option:1
Enter Position to insert:2
Enter Value to insert:99
List Elements:
30 99 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4
Page
}
void insert(int p,int v)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next==null)
add(v);
else
{
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next.prev=temp;
ptr.next=temp;
temp.prev=ptr;
}
}
void del(int p)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next.next==null)
{
temp=last;
last=last.prev;
last.next=null;
}
else
{
temp=ptr.next;
ptr.next=ptr.next.next;
ptr.next.prev=ptr;
}
temp=null;
}
void show()
{
System.out.println("\nList Elements:Left to Right");
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.println("\nList Elements:Right to Left");
for(node ptr=last;ptr.prev!=null;ptr=ptr.prev)
System.out.print("\t"+ptr.x);
}
}
Class DListTest
{
public static void main(String as[]) throws Exception
{
String con="";
int x,op,p,v;
Page
6
Page
Page
30
4.STACK USING ARRAY
1. Program to implement PUSH and POP operations on Stack using array method.
class Stack
{
private static int MAX=10;
private int a[]=new int[MAX];
int top;
Stack()
{
top=0;
}
public void push(int v)
{
if(top<max)</max)
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop()
{
if(top>0)
return a[--top];
else
{
System.out.println("Underflow");
return -1;
}
}
}
class StackArray
{
public static void main(String as[])
{
Stack s1=new Stack();
s1.push(30);
s1.push(40);
s1.push(50);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}
/* Output */
50
40
30
5. ARTHIMETIC EXPRESSION EVALUTION USING STACK
import java.io.*;
import java.util.*;
class Stack
{
Page
Page
break;
case '*':c=a*b;
break;
case '/':c=a/b;
break;
}
s1.push(c);
}
else
s1.push(Integer.parseInt(s));
}
System.out.println("Result="+s1.pop());
}
}
/* Output */
Enter Postfix expression:2,3,*,4,2,/,+
Result=8
6. QUEUES IMPLEMENTATION USING ARRAY
Program to implement insert and delete operations on Queue using array method.
class Queue
{
private static int MAX=10;
private int a[]=new int[MAX];
int front,rear;
Queue()
{
front=rear=0;
}
public void insert(int v)
{
if(rear<max)</max)
a[rear++]=v;
else
System.out.println("Overflow");
}
public int del()
{
if(front!=rear)
return a[front++];
else
{
System.out.println("Underflow");
return -1;
}
}
}
class QArray
{
public static void main(String as[])
{
Queue q1=new Queue();
q1.insert(30);
q1.insert(40);
Page
10
q1.insert(50);
System.out.println(q1.del());
System.out.println(q1.del());
System.out.println(q1.del());
}
}
/* Output */
30
40
50
7.QUEUE OPERATIONS WITH LINKED LIST
Program to implement insert and delete operations on Queue using linked list method
class node
{
public int x;
public node next;
}
class Queue
{
public node front,rear;
Queue()
{
front=rear=null;
}
void insert (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
if(front==null)
front=rear=temp;
else
{
rear.next=temp;
rear=temp;
}
}
int del()
{
int v=front.x;
node temp=front;
front=front.next;
temp=null;
return v;
}
}
class QueueList
{
public static void main(String as[])
{
Queue q1=new Queue();
q1.insert(30);
q1.insert(40);
11
Page
q1.insert(50);
System.out.println(q1.del());
System.out.println(q1.del());
System.out.println(q1.del());
}
}
/* Output */
30
40
50
Page
12
if(isEmpty())
{
throw new EmptyDequeException("Deque is empty.");
}
DNode first= header.getNext();
int o = first.getElement();
DNode second = first.getNext();
header.setNext(second);
second.setPrev(header);
size--;
return o; // replace this line with your code
}
public int removeLast() throws EmptyDequeException
{
if(isEmpty())
{
throw new EmptyDequeException("Deque is empty.");
}
DNode last = trailer.getPrev();
13
Page
int o = last.getElement();
DNode secondtolast = last.getPrev();
trailer.setPrev(secondtolast);
secondtolast.setNext(trailer);
size--;
return o;
}
} // end class
output
adding at front: 34
adding at front: 67
adding at front: 29
adding at front: 765
removed from front: 765
removed from front: 29
removed from front: 67
underflow!! unable to remove. - See more at:
8.Linear search and binary search
/*
Program to search for a number in an array entered by the user using
either Linear Search or Binary Search.
*/
import java.io.*;
class searchArray
{
int a[];
int n;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public searchArray(int nn) // Constructor
{
a = new int[nn];
n = nn;
}
public static void main(String args[]) throws IOException
{
System.out.print("\nEnter the size of the array : ");
int nn = Integer.parseInt(br.readLine());
searchArray call = new searchArray(nn);
System.out.println("\nEnter " +nn +" elements :");
call.readArray();
// Ask for the search technique
System.out.println("Choose Search Technique :\n");
System.out.println("1 : Linear Search");
System.out.println("2 : Binary Search (the array should be
sorted in ascending order)");
System.out.print("\nYour Choice : ");
int choice = Integer.parseInt(br.readLine());
int v;
switch(choice)
{
Page
14
case 1:
System.out.print("\nEnter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.linearSearch(v);
break;
case 2:
System.out.print("\nEnter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.binarySearch(v);
break;
default :
System.out.println("\nInvalid Choice !");
break;
}
}
public void readArray() throws IOException
{
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(br.readLine());
}
public void linearSearch(int v)
{
int f=-1;
for(int i=0;i<n;i++)
{
if(a[i]==v)
{
f=i;
break;
}
}
if(f==-1)
System.out.println("\n" +v +" NOT found !");
else
System.out.println("\n" +v +" is in location " +f);
}
public void binarySearch(int v)
{
int f=-1;
int l=0,m=0,u=n-1;
while(l<=u && f==-1)
{
m = (l+u)/2;
if(a[m]==v)
f = m;
else
if(a[m]>v)
u = m-1;
else
l = m+1;
}
if(f==-1)
7System.out.println("\n" +v +" NOT found !");
Page
15
else
System.out.println("\n" +v +" is in location " +m);
}
}
9. Quick sort implementation
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
public class QuickSort {
Page
16
quicksort(list, 0, list.length-1);
return list;
String list="";
int i=0,n=0;
QuickSort s= new QuickSort();
ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}
elementlist=quicksort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Quick Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
10. java program to implement merge sort
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
public class MergeSort {
17
Page
Page
18
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}
elementlist=mergeSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Merge Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
11.Write a program on Binary Search Tree operations(insertion, deletion and
traversals)
/*
* Java Program to Implement Binary Search Tree
*/
import java.util.Scanner;
/* Class BSTNode */
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
}
/* Class BST */
class BST
{
private BSTNode root;
/* Constructor */
public BST()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
19
Page
data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
Page
20
}
/* Function to insert data recursively */
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
/* Functions to delete data */
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
p2 = rt;
p = rt;
while (p.getLeft() != null)
}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;
21
Page
p = p.getLeft();
p.setLeft(lt);
return p2;
}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BSTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Functions to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BSTNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval)
r = r.getLeft();
else if (val > rval)
r = r.getRight();
else
{
22
}
found = search(r, val);
}
return found;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
private void preorder(BSTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(root);
}
private void postorder(BSTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}
/* Class BinarySearchTree */
public class BinarySearchTree
Page
found = true;
break;
23
Page
24
Page
Page
25
Page
26
Graph g = new Graph(); // Assume 0,1,2,3,4 are the indexes of A,B,C,D,E respectively.
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addVertex('E');
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(4, 1);
g.addEdge(1, 3);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
System.out.print("Visits: ");
g.bfs();
System.out.println();
}
}
Graph Traversals: Non-Recursive DFS************************
class Stack
{
private final int SIZE = 20;
private int[] st;
private int top;
public Stack()
{
st = new int[SIZE];
top = -1;
}
public void push(int j)
{
st[++top] = j;
}
public int pop()
{
return st[top--];
}
public int peek()
{
return st[top];
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Vertex
{
public char label;
public boolean visited;
public Vertex(char label)
{
this.label = label;
Page
27
visited = false;
}
}
class Graph
{
private final int MAX = 20;
private Vertex vertex[];
private int adjMat[][];
private int n;
private Stack stk;
public Graph()
{
vertex = new Vertex[MAX];
adjMat = new int[MAX][MAX];
n = 0;
for(int y=0; y<MAX; y++)
for(int x=0; x<MAX; x++)
adjMat[x][y] = 0;
stk = new Stack();
}
public void addVertex(char lab)
{
vertex[n++] = new Vertex(lab);
}
public void addEdge(int source, int destination)
{
adjMat[source][destination] = 1;
adjMat[destination][source] = 1;
}
public void displayVertex(int v)
{
System.out.print(vertex[v].label);
}
public void dfs()
{
vertex[0].visited = true;
displayVertex(0);
stk.push(0);
while( !stk.isEmpty() )
{
int v = getUnvisitedVertex( stk.peek() );
if(v == -1)
stk.pop();
else
{
vertex[v].visited = true;
displayVertex(v);
stk.push(v);
}
}
for(int j=0; j<n; j++)
vertex[j].visited = false;
}
Page
28