#1. complete program for singly linked list

46
#1. Complete Program for Singly Linked List // This program is summation of all the sub function we have covered from 1-12 /***************************************************************************** @Mukesh Mann dated 27-01-2020. *******************************************************************************/ #include <stdio.h> /* Lets create structure of the node*/ struct node { int data; struct node *link; }*head; // Creating a global head pointer of struct type /* lets declare a function to create nodes*/ void createnode(int n); void inseratbegning(); void inseratend(); void traverselist(); void inseratanyindex(); void deletnodefrombegning(); void deletelastnode(); void deleteatanyindex(); void movelastnodetofront(); struct node * Reverseiterative(struct node *); void ReverseusingRecursion(struct node *,struct node *); //void struct node *ReverseusingRecurssion(struct node); /* lets call main function */ int main() { int n; printf("Enter number of node\n\n"); scanf("%d", &n); createnode(n); printf("Inserting a new node with value 40 at the begning of list\n\n"); inseratbegning(); printf("Inserting a new node with value 70 at the end of list\n\n"); inseratend(); printf("\nTraversing the created list\n"); traverselist(); printf("Inserting a new node with value 90 after node 2 in the linked list\n\n"); inseratanyindex(); printf("After inserting current list is as under\n\n "); traverselist();

Upload: others

Post on 10-May-2022

16 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: #1. Complete Program for Singly Linked List

#1. Complete Program for Singly Linked List // This program is summation of all the sub function we have covered from 1-12 /***************************************************************************** @Mukesh Mann dated 27-01-2020. *******************************************************************************/ #include <stdio.h> /* Lets create structure of the node*/ struct node { int data; struct node *link; }*head; // Creating a global head pointer of struct type /* lets declare a function to create nodes*/ void createnode(int n); void inseratbegning(); void inseratend(); void traverselist(); void inseratanyindex(); void deletnodefrombegning(); void deletelastnode(); void deleteatanyindex(); void movelastnodetofront(); struct node * Reverseiterative(struct node *); void ReverseusingRecursion(struct node *,struct node *); //void struct node *ReverseusingRecurssion(struct node); /* lets call main function */ int main() { int n; printf("Enter number of node\n\n"); scanf("%d", &n); createnode(n); printf("Inserting a new node with value 40 at the begning of list\n\n"); inseratbegning(); printf("Inserting a new node with value 70 at the end of list\n\n"); inseratend(); printf("\nTraversing the created list\n"); traverselist(); printf("Inserting a new node with value 90 after node 2 in the linked list\n\n"); inseratanyindex(); printf("After inserting current list is as under\n\n "); traverselist();

Page 2: #1. Complete Program for Singly Linked List

printf("Deleteing firt node from list\n"); deletnodefrombegning(); printf("After deleteing current list values are\n\n "); traverselist(); printf("----------------------------------Delete node from last--------------------\n"); deletelastnode(); printf("After deleteing last node the current list values are\n\n "); traverselist(); printf("----------------------------------Delete node WITH VALUE =3 IN THE LIST--------------------\n"); deleteatanyindex(); printf("After deleteing node WITH VALUE =3; the current list values are\n\n "); traverselist(); printf("Move last node to front of node\n\n "); movelastnodetofront(); printf("----------------------AfterMoving last node to front the list is --------------\n\n "); traverselist(); printf("----------------------An Iterative verison to reverse data in linked list --------------\n\n "); //*Reverseiterative function will return a pointer and takes a pointer head= (*Reverseiterative)(head); traverselist(); printf("----------------------A Recursive verison to reverse data in linked list --------------\n\n "); //*Reverseiterative function will return a pointer and takes a pointer ReverseusingRecursion(NULL,head); traverselist(); return 0; } void createnode(int n) { int data ; struct node *temp; /* lets create first node using malloc */ head=(struct node*)malloc(sizeof(struct node)); if(head == NULL) { printf("Memory not allocated "); return; }

Page 3: #1. Complete Program for Singly Linked List

printf("Enter first node data "); scanf("%d", &data); temp=head; head-> data = data; head->link=NULL; for(int i=2; i<=n; i++) { struct node *NewNode=(struct node *)malloc(sizeof(struct node)); if(NewNode== NULL) { printf("Memory not allocated "); break; } printf("Enter node data "); scanf("%d", &data); NewNode->data=data; NewNode->link=NULL; temp->link=NewNode; // linking current node with NewNode temp = temp->link; // Moving temp node to NewNode location } printf("List created successfuly!\n"); } /***** traverselist function *****/ void traverselist() { struct node *temp=head; int i=1; while(temp) { printf("Printing %d Element of Linked List %d\n",i,temp->data); i++; temp= temp->link; } } /***** inseratbegning function *****/ void inseratbegning() {

Page 4: #1. Complete Program for Singly Linked List

printf("\nLets insert a node at the begninig\n"); struct node *mynode; mynode=(struct node *)malloc(sizeof(struct node)); mynode->link=head; mynode->data=40; head=mynode; printf("New Node Inserted Successfuly at the begning!\n"); } /***** inseratEnd function *****/ void inseratend() { printf("\nLets insert a node at the End\n"); struct node *mynode; struct node *temp=head; mynode=(struct node *)malloc(sizeof(struct node)); while(temp->link!=NULL) { temp=temp->link; } temp->link=mynode; mynode->link=NULL; mynode->data=70; printf("New Node Inserted Successfuly at the End!\n"); } /***** inseratanyindex function *****/ void inseratanyindex() { printf("\nLets insert a node at the End\n"); struct node *mynode; struct node *temp=head; mynode=(struct node *)malloc(sizeof(struct node)); while(temp->data!=2) { temp=temp->link;

Page 5: #1. Complete Program for Singly Linked List

} mynode->link=temp->link; temp->link=mynode; mynode->data=90; printf("New Node Inserted Successfuly at the after node 2!\n"); } /***** deletnodefrombegning() *****/ deletnodefrombegning() { struct node *temp=head; if(head== NULL) { printf("THERE IS NO NODE TO DELETE\n"); } if(head->link==NULL) // there is only one node { free(head); head=NULL; } head=head->link; free(temp); } /***** deletelastnode() *****/ deletelastnode() { struct node *temp=head; while(temp->link->link!=NULL) { temp=temp->link; } temp->link->link=NULL; free(temp->link); temp->link=NULL; } /***** deleteatanyindex() *****/ deleteatanyindex() { struct node *temp=head; while(temp->link->data!=3)

Page 6: #1. Complete Program for Singly Linked List

{ temp=temp->link; } struct node *temp1=temp->link; temp->link=temp1->link->link; free(temp1); temp1= NULL; } /***** Moving Last node to the front of linked list movelastnodetofront() *****/ // Lets have two pointer (p,q) one will be one step ahead of other; // the moment one pointer (p) reaches last node ; point its link to head, // and put null into q ; movelastnodetofront() { struct node *p,*q; p=head; while(p->link != NULL) { q=p; p=p->link; } q->link= NULL; p->link=head; head=p; } /***** Reverseing content of linked list using Iterative version Reverseiterative() is a function pointer which returns a pointer to a structure and it takes head as its initial pointer as parameter *****/ struct node *Reverseiterative(struct node *curr) { struct node *prev= NULL; struct node *nextnode= NULL; while(curr) { nextnode =curr->link; curr->link= prev; prev=curr; curr=nextnode;

Page 7: #1. Complete Program for Singly Linked List

} head=prev; printf("value of current node is%d",head); return prev; } /***** Reverseing content of linked list using Recursion ReverseusingRecursion() is a function which returns a pointer to a structure and it takes NULL in prev node and head in curr. *****/ void ReverseusingRecursion(struct node *prev, struct node *curr) { if(curr) { ReverseusingRecursion(curr,curr->link); curr->link=prev; } else head=prev; }

#2. Reverse the elements of linked list using Recursive Version /***** Reversing content of linked list using Recursion ReverseusingRecursion() is a function which returns a pointer to a structure and it takes NULL in prev node and head in curr. *****/ void ReverseusingRecursion(struct node *,struct node *); // Global Declaration of function ReverseusingRecursion(NULL,head); // Calling ReverseusingRecursion() function from main() void ReverseusingRecursion(struct node *prev, struct node *curr) { if(curr) { ReverseusingRecursion(curr,curr->link); curr->link=prev; } else

Page 8: #1. Complete Program for Singly Linked List

head=prev; }

#3. Doubly Linked List :1- Creating a Structure node for doubly Linked List #include <stdio.h> /* Lets create structure of the node*/ struct node { int data; struct node *prev; struct node *next; }*head; // Creating a global head pointer of struct type

#4.Doubly Linked List :2- Create and traverse in doubly Linked List /***************************************************************************** Doubly linked list creation ! @Mukesh Mann dated 10-02-2020. *******************************************************************************/ #include <stdio.h> /* Lets create structure of the node*/ struct node { int data; struct node *prev; struct node *next; }*head; // Creating a global head pointer of struct type /* lets declare a function to create nodes*/ void createnode(); void traverselist(); int main() { int n; printf("Enter number of node\n\n"); scanf("%d", &n); createnode(n); printf("\nTraversing the created list\n"); traverselist(); } void createnode(int n)

Page 9: #1. Complete Program for Singly Linked List

{ struct node *temp; int x ; //struct node *temp; /* lets create first node using malloc */ head=(struct node*)malloc(sizeof(struct node)); if(head == NULL) { printf("Memory not allocated "); return; } printf("Enter first node data "); scanf("%d", &x); temp=head; temp->prev=NULL; temp->next=NULL; temp->data = x; int k; for(int i=2; i<=n; i++) { struct node *NewNode=(struct node *)malloc(sizeof(struct node)); if(NewNode== NULL) { printf("Memory not allocated "); break; } printf("Enter node data "); scanf("%d", &k); NewNode->data=k; NewNode->next=NULL; NewNode->prev=temp; temp->next=NewNode; //head->next->prev=head; temp=temp->next; //printf("Printing Element of Linked List %d\n",head->data); } printf("List created successfuly!\n"); } /***** traverselist function

Page 10: #1. Complete Program for Singly Linked List

*****/ void traverselist() { struct node *temp; temp=head; // printf("Value in temp is %d and temp points to %d", temp,temp->data); int i=1; while(temp!=NULL) { printf("Printing %d Element of Linked List - %d\n",i,temp->data); i++; temp=temp->next; } return;

}

Data Structure- 1. Stacks Introduction As you know that a program is supposed to take some input and is expected to give some output ! The input and the output to a program is given in some format, that format is what we called as data structure! You can think if we give a unsorted array to a sorting program than the time taken to sort the elements is more as compared to a sorted input array ! this means that the format of input data plays an important role as far as far as performance of an algorithm is considered. ! In this respect the first and traditional way of giving the data was using - STACK. A stack is a data structure ( i.e., a type of input format) which follows LIFO property, that is the last element is popped out first from the top of the stack. The main application of stacks are in 1. Recursion :- Remember how recursive calls for a function is made by creating a stack activation record 2. Text Editors- use stacks for Redo & undo Operations. 3. Brower's use stacks for remembering which page is visited and then going back( i,e, POP ) In this article we will study how stack push and pop operation.

Page 11: #1. Complete Program for Singly Linked List

Data Structure- 2. Stacks Push and POP Operation As you know that in stack we always perform push and pop f an element from the top of the stack , here is the code to do the same /****************************************************************************** Push and Pop Operation in Stack ! @Mukesh Mann dated 16-02-2020 *******************************************************************************/ #include <stdio.h> int top=-1; // Delaring a Top variable initially pointing to -1 int stack [10]; // a stack array of 10 elements int main() { // Push operation in stack array for (int i=0; i<=10; i++) { top=top+1; stack[top]=i; } // Printing content of stack array for (int i=1; i<=10; i++) { printf(" The element in the stack are %d\n",stack[i]); } // pop operation in stack array for (int i=1; i<=10; i++) { printf(" poping %d element %d\n",i, stack[top]); top=top-1; } printf(" After perfroming pop operation the content of stack is %d\n",stack[top]); return 0; }

Page 12: #1. Complete Program for Singly Linked List

Data Structure- 3. Stacks Push and POP Operation using Linked List As you know that in a stack the push and pop operation always done from the top, so if you imagine each index of stack a linked list than the push operation is nothing more than inserting a node at the front of list and pop operation is nothing but deletion a node from the front of list ( i.e., TOP) here is the code for you ! Note that we have used power of recursion here to push the elements in the stack ! /****************************************************************************** Stacks Push and POP Operation using Linked List @Mukesh Mann dated 16-02-2020 *******************************************************************************/ #include <stdio.h> /* Lets create structure of the node*/ struct node { int data; struct node *link; }*head= NULL; // Creating a global head pointer of struct type createnode(int n, int item) { if(n){ int data ; struct node *temp; /* lets create first node using malloc */ temp=(struct node*)malloc(sizeof(struct node)); if(temp == NULL) { printf("Memory not allocated "); return; } temp-> data = item; temp->link=head; head= temp; // now suppose second element is 1 more than previous createnode(n-1,item+1); return head;

Page 13: #1. Complete Program for Singly Linked List

} } int main() { int n, item; printf("Enter number of elemens to be pushed in stack\n\n"); scanf("%d", &n); printf("Enter the item \n\n"); scanf("%d", &item); struct node *temp1=createnode(n,item); / holding returned value of head which is a pointer for(int i=0;i<n;i++) { head= temp1; printf("Top %d in the stack is %d\n", i, temp1->data); temp1= temp1->link; } return 0; } // The deletion of an element from the stack using concept of linked list is left as an exercise for you

Data Structure- 4. Queue Concept

Like Stack data Structure ! Queue is also another type of Data Structure which follows the concept of FIFO ! Thas is the element which comes first will be deleted first! Concept to code !- We maintain two variables called front and Rear, The Front will always point to the first element in the queue and the Rear will element will always point to the current element that is just inserted into the queue. If you will follow this than lets suppose we are given the following list of element <5,6,7,8> then in queue it will look like, Initially

Page 14: #1. Complete Program for Singly Linked List

Thus whenever you wish to insert ( Enqueue) an element then simply increment the rear and put the item there ! when you wish to delete ( Dequeue ) the item the you simply increment the front and take out the item from there! Thus here is the Code to push and pop an element from the queue ! /****************************************************************************** Queue Concept using an Array ! @Mukesh Mann dated 16-02-2020 *******************************************************************************/ /* * C Program to Implement a Queue using an Array */ #include <stdio.h> #define MAX 50 void insert(); void delete(); void display(); int queue_array[MAX]; int rear = - 1; int front = - 1; main() { int choice; while (1)

Page 15: #1. Complete Program for Singly Linked List

{ printf("1.Insert element to queue \n"); printf("2.Delete element from queue \n"); printf("3.Display all elements of queue \n"); printf("4.Quit \n"); printf("Enter your choice : "); scanf("%d", &choice); switch (choice) { case 1: insert(); break; case 2: delete(); break; case 3: display(); break; case 4: exit(1); default: printf("Wrong choice \n"); } /* End of switch */ } /* End of while */ } /* End of main() */ void insert() { int add_item; if (rear == MAX - 1) printf("Queue Overflow \n"); else { if (front == - 1) /*If queue is initially empty */ front = 0; printf("Inset the element in queue : "); scanf("%d", &add_item); rear = rear + 1; queue_array[rear] = add_item; } } /* End of insert() */ void delete() { if (front == - 1 || front > rear)

Page 16: #1. Complete Program for Singly Linked List

{ printf("Queue Underflow \n"); return ; } else { printf("Element deleted from queue is : %d\n", queue_array[front]); front = front + 1; } } /* End of delete() */ void display() { int i; if (front == - 1) printf("Queue is empty \n"); else { printf("Queue is : \n"); for (i = front; i <= rear; i++) printf("%d ", queue_array[i]); printf("\n"); } } /* End of display() */

Data Structure- 5 Queue Concept using Circular Array

// In this article we will Learn concept of circular array to

implement the queue concept because as we can see the in linear array there is

a no way to store new item even if there is a space after deleting an element !

with circular array w will use MAX-1 index of array and initially we will put front

and rear to index zero position !

1. when we need to insert a data we just increment the rear and insert the data !

2. When we need to delete the data we just increase the front and print the data!

Page 17: #1. Complete Program for Singly Linked List

Only important point is that when during insertion if rear== front then it means the queue is

full now and we will put rear one position back , if rear =0 then one position back is MAX-1; and

if rear != 0 then one position back is rear-1;

In order to move rear and front we will use mod operator!

/******************************************************************************

Queue Concept using Circular Array !

@Mukesh Mann dated 16-02-2020

*******************************************************************************/

#define MAX 4

enqueue(int);

//void delete();

void display();

int queue_array[MAX];

int rear = 0;

int front = 0;

Page 18: #1. Complete Program for Singly Linked List

enqueue(int item)

{

//int item;

rear=(rear+1)%MAX;

if (front==rear)

{ printf("Queue Overflow \n"); if(rear==0) { rear=MAX-1; } else { rear=rear-1;} return; } else { queue_array[rear]= item; printf("iTEM INSERTED is %d\n",queue_array[rear]); return; } } /* End of Enqueue() */ deqeue() { if(front==rear) { printf("Queue is empty on"); return -1; } else { front=(front+1)%MAX; int item= queue_array[front]; printf("Deleted Item is %d\n",item); return item; } } /* End of deqeue() */ main() {

Page 19: #1. Complete Program for Singly Linked List

// Here we try to insert 3 item using a loop // initially front and rear are point to zero and we will utilize only max-1 index of circular array for (int i = front; i <= MAX-1; i++){ enqueue(i); } for (int i = front; i <= MAX-1; i++){ deqeue(); } }

#1.Trees basics Tree In this unit Let me briefly tell you that why we are studying this ADT As you know that Searching an element using in a linked list takes ~0(n) time. How? Lets assume that you wish to search an element named "A" in a given linked list ( Obviously LL is a non linear data Structure) which contains elements A,B,D,E . What will be the worst case ( This is when The Element is placed at the last in the linked list) so how much time it will take to search this A now, Obviously you have to traverse each element and then you will be able to find A ., How many elements are there in the list ? 4 here , so if elements are n then how much time you will take in worst case = ~0(n). Fine! Now if we can reduce this time to some Log time Don't you think it is more wonderful ? How, Lets use the concept of one more non linear ADT called Trees. A tree is a non linear structure in which each node is connected with some other node (forming parent child relationship) to form a hierarchical structure. the point is to reduce the searching time ! But even before that lets try to understand different types of trees with their terminologies !

1. We have discussed linear data structures, such as, Arrays, Strings, Stacks, and Queues.

2. Now, we will learn about a Non-Linear Data Structure called TREE.

3. A tree is a structure which is mainly used to store data that is hierarchical in nature. First, we will understand general trees and then Binary Trees.

4. These binary trees are used to form binary search trees and heaps. They are widely used to manipulate Arithmetic Expressions, Construct Symbol Tables, and for Syntax Analysis.

Page 20: #1. Complete Program for Singly Linked List
Page 21: #1. Complete Program for Singly Linked List
Page 22: #1. Complete Program for Singly Linked List
Page 23: #1. Complete Program for Singly Linked List
Page 24: #1. Complete Program for Singly Linked List
Page 25: #1. Complete Program for Singly Linked List
Page 26: #1. Complete Program for Singly Linked List
Page 27: #1. Complete Program for Singly Linked List

Now Hope you understood The definition ! Please keep in mind that some books follow slightly different convention while defining the types of trees Now lets try to explore why the complexity turns out to be log(n) in searching for an element.

Page 28: #1. Complete Program for Singly Linked List

But ! wait what if the tree is skewed !

Page 29: #1. Complete Program for Singly Linked List
Page 30: #1. Complete Program for Singly Linked List

So, What will be the advantage of using trees if its complexity turns out to be ~0(n); Yes you are right their is no advantage if the tree is skewed but if it is complete or almost complete than you can take log(n) time advantage over ~o(n). Ok! Hope You are now clear about different terminologies used in Trees ! and the reason we are using this ADT But wait I know that you reduced the time by using Trees but it is on the cost of inserting and deletion ! in Trees both operation involves traversing a node and then deletion/insertion. So in wort case A node is present at last and thus you need to traverse all the nodes in order to reach that node. If visiting a node takes C amount then to visit n nodes will take ~=Cx o(n) =O()n Conclusion - Trees reduces searching (log (n) , in linked list = O(n)) nut insertion and deletion time increases that is = O(n) which is O(1) in case of lionked list.

2#Trees Traversal

In this Unit we will Learn about Trees ADT and how to Implement them

Why to use Tree ADT. Theoretical understanding regarding its time has already been

seen why we are using trees! Remember the time complexity in searching log (n) over

the cost of insertion and deletion (o(n) ) . Have you observed in your computer how files

are organised in a tree structure

Page 31: #1. Complete Program for Singly Linked List

Fine ! Observe some other interesting applications of Trees!

Page 32: #1. Complete Program for Singly Linked List
Page 33: #1. Complete Program for Singly Linked List
Page 34: #1. Complete Program for Singly Linked List

Now let’s start this journey by finding different possibilities with which we can make trees

See there are two scenarios - 1) if you are given some nodes without label and 2) with

labels

can you draw number of binary trees possible in each case?

A binary tree is one which is having degree of at most 2 , thus node with degree 0,1,2 are

binary

Page 35: #1. Complete Program for Singly Linked List
Page 36: #1. Complete Program for Singly Linked List
Page 37: #1. Complete Program for Singly Linked List
Page 38: #1. Complete Program for Singly Linked List
Page 39: #1. Complete Program for Singly Linked List
Page 40: #1. Complete Program for Singly Linked List
Page 41: #1. Complete Program for Singly Linked List
Page 42: #1. Complete Program for Singly Linked List
Page 43: #1. Complete Program for Singly Linked List

3_Tree Traversals Lab /******************************************************************************

Trees Concepts ! Inoder Traversal

@Mukesh Mann dated 23-03-2020

*******************************************************************************/

/******************************************************************************

*******************************************************************************/

#include <stdio.h>

typedef struct node

{

int data;

struct node *left;

struct node *right;

}Node;

// Lets try to creat a root node first

int * create()

{

int x;

Node *newnode=(Node*)malloc(sizeof(Node));

printf("Enter the data for the nodes(-1 for no data)");

Page 44: #1. Complete Program for Singly Linked List

scanf("%d", &x);

if(x==-1)

{

//printf("You have not entered any data");

return NULL;

}

newnode->data=x;

printf("Enter the left child data rooted at %d \n",newnode->data);

newnode->left=create();

printf("Enter the right child data rooted at %d\n",newnode->data);

newnode->right=create();

return newnode;

}

void traverse(Node *t)

{

if(!t==NULL)

{

Page 45: #1. Complete Program for Singly Linked List

printf("Left child data is %d ",t->data);

//printf("Left child data is %d",t->left->data);

//printf("right child data is %d",t->left->data);

traverse(t->left);

t=t->right;

}

if(!t==NULL)

{

printf("Right child data is %d\n",t->data);

//printf("Left child data is %d",t->left->data);

//printf("right child data is %d",t->left->data);

traverse(t->right);

//t=root;

}

}

void Inorder(Node *t)

{

//printf("In order traversal is" );

if(t)

Page 46: #1. Complete Program for Singly Linked List

{

Inorder(t->left);

printf(" %d",t->data);

Inorder(t->right);

}

}

int main()

{

Node *root=create();

Node *t=root;

printf("Root child is %d\n ",t->data);

traverse(t);

Inorder(t);

printf(" is the order traversal \n\n" );

return 0;

}