Data Structure Lab Programs

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 26

Stack Definition: In computer science, a stack is a last in, first out(LIFO) abstract data type and data structure.

A stack can have any abstract data type as an element, but is characterized by only two fundamental operations, the push and the pop. (or) A collection of items in which only the most recently added item may be removed. The latest added item is at the top. Basic operations are push and pop. Often top and is Empty are available, too. Also known as "last-in, first-out" or LIFO. Push: The push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is empty. Pop: The pop operation removes an item from the top of the list, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty list. Stack Applications: 1. Expression evaluation. 2. Backtracking (game playing, finding paths, exhaustive searching). 3. Memory management, run-time environment for nested language features. Alogarithm steps: 1. Expression evaluation. 2. Backtracking (game playing, finding paths, exhaustive searching). 3. Memory management, run-time environment for nested language features. Alogarithm steps: Step 1: create a list. i) Create a new empty node top. ii) Read the stack element and store it in top's data area. iii) Assign top's link part as NULL (i.e. top->link=NULL). iv) Assign temp as top (i.e. temp=top).

Step 2: Read next stack operation. i) If it is Create then go to step1. ii) If it is Push then it process following steps a) Check Main memory for node creation. b) Create a new node top. c) Read the stack element and store it in top's data area. d) Assign top's link part as temp (i.e. top->link=temp). e) Assign temp as top (i.e. temp=top). iii) If it is pop then it process following steps a) If top is NULL then display stack is empty. b) Otherwise assign top as temp (i.e. top=temp, bring the top to top position) c) Assign temp as temp's link. (i.e. temp=temp->link, bring the temp to top's previous position). d) Delete top from memory. iv) If it is traverse then process the following steps a) Bring the top to stacks top position(i.e. top=temp) b) Repeat until top becomes NULL i) Display the top's data. ii) Assign top as top's link (top=top->link).

C Program To Implement Stack Data Structure Using Single Linked List:


#include<stdio.h> #include<conio.h> #include<alloc.h> #include<stdlib.h> /* Node decleration */ struct node { int data;

struct node *link; //to maintain the link other nodes }; struct node *top,*temp; void create(); void push(); void pop(); void display(); /* create function create the head node */ void create() { printf("\nENTER THE FIRST ELEMENT: "); top=(struct node *)malloc(sizeof(struct node)); scanf("%d",&top->data); top->link=NULL; temp=top; } /* display function visit the linked list from top to end */ void display() { top=temp; // bring the top to top position printf("\n"); while(top!=NULL) { printf("%d\n",top->data); top=top->link; // Now top points the previous node in the list } } void push() { printf("\nENTER THE NEXT ELEMENT: "); top=(struct node *)malloc(sizeof(struct node)); scanf("%d",&top->data); top->link=temp; temp=top; } void pop() { if(temp==NULL) { printf("\nSTACK IS EMPTY\n"); } else {

top=temp; printf("\nDELETED ELEMENT IS %d\n",temp->data); temp=temp->link; free(top); } } void main() { int ch; clrscr(); while(1) { printf("\n\n 1.CREATE \n 2.PUSH \n 3.POP \n 4.EXIT \n"); printf("\n ENTER YOUR CHOICE : "); scanf("%d",&ch); switch(ch) { case 1: create(); display(); break; case 2: push(); display(); break; case 3: pop(); display(); break; case 4: exit(0); } } }

SAMPLE INPUT AND OUTPUT: STACK 1. CREATE 2. PUSH 3. POP 4. EXIT ENTER YOUR CHOICE : 1 ENTER THE FIRST ELEMENT : 10 10 STACK 1. CREATE

2. PUSH 3. POP 4. EXIT ENTER YOUR CHOICE: 2 ENTER THE NEXT ELEMENT: 30 10 30 STACK 1. CREATE 2. PUSH 3. POP 4. EXIT ENTER YOUR CHOICE: 3 DELETED ELEMENT IS 30 STACK 1. CREATE 2. PUSH 3. POP 4. EXIT ENTER YOUR CHOICE: 3 DELETED ELEMENT IS 10 STACK 1. CREATE 2. PUSH 3. POP 4. EXIT ENTER YOUR CHOICE: 3 STACK IS EMPTY.

Implementation Of Double Linked List:


Definition: A variant of a linked list in which each item has a link to the previous item as well as the next. This allows easily accessing list items backward as well as forward and deleting any item in constant time. Also known as two-way linked list, symmetrically linked list. A doubly linked list is a linked list in which each node has three fields namely data field, forward link (Flink) and backward link (Blink). Flink points to the successor node in the list whereas Blink points to the predecessor node.

Advantages: 1. Deletion process is easier 2. Additional pointer for previous node is not nessary. 3. Backwarding and forwarding traverse are possible.

Disadvantages : 1. More Memory space is required since it has two pointers. Alogrithm steps: Step 1: Read the list operation. Step 2: If operation is Create then process the following steps. 1. Create the new node and allocate memory for the new node. 2. Read the data in the new node. 3. Assign Flink and Blink as NULL. 4. Assign current as new. Step 3: If operation is Insertion do the following steps. i) Check insertion at beginning is true then

1. Create the new node and allocate memory for the new node 2. Read the data in the new node. 3. Move the current node to start position 4. Assign new->Blink =Null 5. Assign new->Flink=current 6. Now assign current->Blink=new ii) Insertion at between nodes is true then

1. Create the new node and allocate memory for the new node 2. Read the data in the new node.

3. Move the current node required position 4. Assign new nodes Blink=current. 5. Assign new nodes Flink=current->Flink 6. Assign current nodes Flink =new iii) Insertion at between nodes is true then

1. Create the new node and allocate memory for the new node. 2. Read the data in the new node. 3. Move the current node to end position. 4. Assign current nodes Flink =new. 5. Assign news Blink as current. 6. Assign news Flink as NULL. 7. Move end pointer to new node. Step 4: If operation is deletion then do the following steps. i). Check deletion at beginning is true then. 1. Move current pointer to start position. 2. Move the start pointer next node in the link. 3. Assign starts Blink as NULL. 4. Reallocate current node from memory. ii) Check deletion between two nodes is true

1. Move the current pointer to required position. 2. Assign currents->Blink->Flink as currents Flink. 3. Assign currentss->Flink->Blink as currents Blink. 4. Reallocate current from memory.

iii) Check deletion at end is true

1. Move the current pointer to end position. 2. Assign currents->Blink->Flink as Null. 3. Reallocate current from memory. 4. Reallocate current from memory. Step 5: If the operation is traversing. i) Check deletion at end is true

1. Move the current pointer to end position. 2. Repeat the following steps until current becomes NULL. 3. Display the data. 4. Current=current->Flink. ii) If Backward traversing then

1. Move the current to end position. 2. Repeat the following steps until current becomes NULL. 3. Display the data. 4. Current=current->Flink.

#include<stdio.h> #include<conio.h> #include<alloc.h> #include<stdlib.h> #define NULL 0 struct linkedlist { int item; struct linkedlist *right,*left; };

typedef struct linkedlist node; void main() { node *start,*end; int choice; int menu(void); node *create(node **lastnode); void display(node *first,node *last); void insert(node **first,node **last); void del(node **first,node **last); clrscr(); printf("\n DOUBLY LINKED LIST"); printf("\n ******************"); do { printf("\n\nMain menu"); printf("\n\n1.Create \n2.Insert \n3.Delete \n4.Display \n5.Exit"); choice =menu(); switch(choice) { case 1: printf("\n Enter the data(-999 to stop):"); start=create(&end); continue; case 2: insert(&start,&end); printf("\n"); continue; case 3: del(&start,&end); printf("\n"); continue; case 4: display(start,end); printf("\n"); continue; case 5: exit(0); default:

printf("\n\nINVALID CHOICE..."); } }while(1); } int menu() { int choice; do { printf("\n Enter your choice:"); scanf("%d",&choice); if(choice<1||choice>5) printf("\n Wrong choice"); }while(choice<1||choice>5); printf("\n"); return(choice); } node *create(node **lastnode) { node *temp,*firstnode; int info; *lastnode=NULL; firstnode=NULL; scanf("%d",&info); while(info!=-999) { temp=(node *)malloc(sizeof(node)); temp->item=info; temp->right=NULL; if(firstnode==NULL) { temp->left=NULL; firstnode=temp; } else { temp->left=(*lastnode); (*lastnode)->right=temp; } (*lastnode)=temp; scanf("%d",&info); } if(firstnode!=NULL) (*lastnode)=temp;

return(firstnode); } void display(node *first,node *last) { printf("\n Forward traversal\n"); while(first!=NULL) { printf("%d\t",first->item); first=first->right; } printf("\n Backward traversal\n"); while(last!=NULL) { printf("%d\t",last->item); last=last->left; } return; } void insert(node **first,node **last) { node *newnode; int newitem; int position; node *temp; int i; printf("\n New data item:"); scanf("%d",&newitem); do { printf("\n Position of insertion:"); scanf("%d",&position); }while(position<=0); if(((*first)==NULL)||(position==1)) { newnode=(node *)malloc(sizeof(node)); newnode->item=newitem; newnode->right=*first; newnode->left=NULL; if((*first)!=NULL) (*first)->left=newnode; else (*last)=newnode; *first=newnode; }

else { i=1; temp=*first; while((i<position-1)&&(temp->right!=NULL)) { i++; temp=temp->right; } newnode=(node *)malloc(sizeof(node)); newnode->item=newitem; newnode->right=temp->right; if(temp->right!=NULL) temp->right->left=newnode; newnode->left=temp; temp->right=newnode; } if(newnode->right==NULL) *last=newnode; } void del(node **first,node **last) { node *temp,*prev; int target; printf("\n Enter the data to be deleted:"); scanf("%d",&target); if(*first==NULL) printf("\n List is empty"); else if((*first)->item==target) { if((*first)->right==NULL) *first=*last=NULL; else { *first=(*first)->right; (*first)->left=NULL; } } else { temp=*first; prev=NULL; while((temp->right!=NULL)&&(temp->item!=target)) { prev=temp;

temp=temp->right; } if(temp->item!=target) printf("\n Element not found"); else { if(temp==*last) *last=prev; else temp->right->left=temp->left; prev->right=temp->right; } } }

Sample Input Output: Main menu 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter your choice:1 Enter the data(-999 to stop): 5 10 15 -999 Main menu 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter your choice:2 New data item:20

Position of insertion: Main menu 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter your choice:4 Forward traversal 5 20 10 15 20 Backward traversal 20 15 10 20 5 Main menu 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter your choice:3 Enter the data to be deleted:5 Main menu 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter your choice:4 Forward traversal 20 10 15 20 Backward traversal 20 15 10 20

Implementation Of Binary Search :

Binary search: Definition: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Advantages: 1. It is faster than linear search. 2. It is astounding for large numbers. Disadvantages:

1. Binary search can interact poorly with the memory hierarchy (i.e. caching), because of its random-access nature. 2. Before searching the elements shorting is necessary.It take some additional overhead to machine. Analysis of the Binary sort: 1. Worest case performance O(log n) 2. Best case performance O(1) 3. Average case performance O( log n) Algorithm steps:

Step 1: Read the elements of the list. Step 2: Sort the input list. Step 3: Find the mid value. Step 4: Look at the element in the middle. If the key is equal to that, the search is finished. Step 5: If the key is less than the middle element, do a binary search on the first half.

Step 6: If it's greater, do a binary search of the second half.

#include<stdio.h> #include<conio.h> void main() { int a[25],i,j,temp,s,n,low,mid,high; clrscr(); printf("\nEnter the Limilt : "); scanf("%d",&n); printf("\n\nEnter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n-1;i++) { for(j=0;j<n-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("\n\nSorted list"); for(i=0;i<n;i++) { printf("\n%d",a[i]); } printf("\n\nEnter the elements to be searched : "); scanf("%d",&s); high=n-1; low=0; while(low<=high) { mid=(low+high)/2; if(s>a[mid]) low=mid+1; else if(s<a[mid]) high=mid-1;

else if(s==a[mid]) { printf("\n\nThe element %d is found",s); getch(); exit(0); } } printf("\n\nThe element %d is not found",s); getch(); }

SAMPLE INPUT AND OUTPUT: Enter the elements 5 4 3 2 1 Sorted list 1 2 3 4 5 Enter the element to be searched : 5 The element 5 is found.

Conversion Of Infix Expression To Postfix Expression:

Infix Expression: Notation in which the operator separates its operands. Eg (a + b) * c. Infix notation requires the use of brackets to specify the order of evaluation. Postfix Expression:

Reverse Polish Notation or Suffix Notation in which the operator follows its operands. Eg a + b * c represented as abc*+. Algorithm steps: 1. Scan the Infix string from left to right. 2. Initialize an empty stack. 3. If the scanned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty push the character to stack. 4. If the scanned character is an Operator and the stack is not empty, compare the precedence of the character with the element on top of the stack (top Stack). If top Stack has higher precedence over the scanned character pop the stack else push the scanned character to stack. Repeat this step as long as stack is not empty and top Stack has precedence over the character. 5. Repeat this step till all the characters are scanned. 6. After all characters are scanned, we have to add any character that the stack may have to the Postfix string. If stack is not empty add top Stack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty.

#include<stdio.h> #include<conio.h> #include<string.h> #include<ctype.h> #include<stdlib.h> #define N 64 #define LP 10 #define RP 20 #define OPERATOR 30 #define OPERAND 40 // Left parentheses precedence. Minimum of all #define LPP 0 // Addition Subtraction precedence. Minimum among all operator precedence #define AP 1 #define SP AP

// Multiplication divisor precedence. #define MP 2 #define DP MP // Remainder precedence. #define REMP 2 #define NONE 9 static char infix[N+1],stack[N],postfix[N+1]; static int top; void infixtopostfix(void); /** POSTFIX CONVERSION FUNCTION **/ int gettype(char); /** TYPE OF EXPRESSION GENERATOR **/ void push(char); /** PUSH FUNCTION **/ char pop(void); /** POP FUNCTION **/ int getprec(char); /** PRECEDENCE CHECKER FUNCTION **/ void main() { char ch; do { top=-1; printf("\nEnter an infix expression\n"); fflush(stdin); gets(infix); infixtopostfix(); printf("\ninfix = %s\npost fix =%s\n",infix,postfix); printf("\nDo you wish to continue\n"); ch=getche(); }while(ch=='Y' || ch=='y'); } void infixtopostfix(void) { int i,p,l,type,prec; char next; i=p=0; l=strlen(infix); while(i<l) { type=gettype(infix[i]); switch(type) { case LP:

push(infix[i]); break; case RP: while((next=pop())!='(') postfix[p++]=next; break; case OPERAND: postfix[p++]=infix[i]; break; case OPERATOR: prec=getprec(infix[i]); while(top>-1 && prec <= getprec(stack[top])) postfix[p++]=pop(); push(infix[i]); break; } i++; } while(top>-1) postfix[p++]=pop(); postfix[p]='\0'; } int gettype(char sym) { switch(sym) { case '(': return(LP); case ')': return(RP); case '+': case '-': case '*': case '/': case '%': return(OPERATOR); default : return(OPERAND); } } void push(char sym) { if(top>N)

{ printf("\nStack is full\n"); exit(0); } else stack[++top]=sym; } char pop(void) { if(top<=-1) { printf("\nStack is empty\n"); exit(0); } else return(stack[top--]); } int getprec(char sym) { switch(sym) { case '(': return(LPP); case '+': return(AP); case '-': return(SP); case '*': return(MP); case '/': return(DP); case '%': return(REMP); default : return(NONE); } }

SAMPLE INPUT AND OUTPUT:

Enter any infix expression 3*6+4*2/5 Infix = 3*6+4*2/5 Post fix =36*42*5/+ Do you wish to continue y Enter an infix expression

Implementation Of Heap Sort:

Sorting: Sorting algorithm is an algorithm that puts elements of a list in a certain order . The mostused orders are numerical order and lexicographical order. Sorting algorithm classification: Computaional complexcity. Memory utilization Stability-Maintaining relative order of records with equal keys. No.of comparisions Methods applied like insertion,exchange,,selection,merging etc. Sorting is a process of linear ordering of list of objects Sorting techniques are categoried into: 1. Internal sorting 2. External sorting Internal sorting: It takes the place in the main memory of a computer. Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc

External sorting: It takes the place in secondary memory of a computer,Since the number of objects to be stored is too large to fit in main memory. Eg:Merge sort,Multiway Merge,Polyphase merge. Heap sort: Heapsort (method) is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case (n log n) runtime. Heapsort is an in-place algorithm, but is not a stable sort. In heap sort the array is interpreted as a binary tree. This method has 2 phases. In phase 1, binary heap is constructed. In phase 2, delete min routine is performed. Analysis of the heap sort: Worest case performance O(n log n) Best case performance O(n log n) Average case performance O(n log n) Advantages of heap sort: 1.It is efficient for sorting large number of elements. 2.It has the advantages of worst case O(N log N) running time. Limitations: 1. It is not a stable sort. 2. It requires more processing time Alogrithm steps: Step1: Read the size of the list Step2: Read the elements of the list Step3: Binary heap construction. 1) Structrue Property:

For any element in array position I,the left child is in position 2i,the right child is in 2i+1,(ie) the cell after the left child. 2) Heap Order Property: The value in the parent node is smaller than or equal to the key value of any of its child node.Build the heap,apply the heap order propery starting from the right. most nonleaf node at the bottom level. Step 4: Delete min routine is performed. The array elements aer stored using deletemin operation,which gives the elements arranged in descending order.

#include<stdio.h> #include<conio.h> int hsort[25],n,i; void adjust(int,int); void heapify(); void main() { int temp; clrscr(); printf("\n\t\t\t\tHEAP SORT"); printf("\n\t\t\t\t**** ****\n\n\n"); printf("\nenter no of elements:"); scanf("%d",&n); printf("\nenter elements to be sorted\n\n"); for(i=1;i<=n;i++) scanf("%d",&hsort[i]); heapify(); for(i=n;i>=2;i--) { temp=hsort[1]; hsort[1]=hsort[i]; hsort[i]=temp; adjust(1,i-1); } printf("\nSORTED ELEMENT\n\n"); for(i=1;i<=n;i++)

printf("%d\n",hsort[i]); getch(); } void heapify() { int i; for(i=n/2;i>=1;i--) adjust(i,n); } void adjust(int i,int n) { int j,element; j=2*i; element=hsort[i]; while(j<=n) { if((j<n)&&(hsort[j]<hsort[j+1])) j=j++; if(element>=hsort[j]) break; hsort[j/2]=hsort[j]; j=2*j; } hsort[j/2]=element; }

SAMPLE INPUT AND OUTPUT: Enter No Of Elements:5 Enter Elements To Be Sorted 5 4 3 2 1 Sorted Element 1 2

3 4 5

You might also like