Sie sind auf Seite 1von 35

DS LAB

PES SCHOOL OF ENGINEERING


1Km before Electronic City, Hosur Road, Bangalore-560100.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION SCIENCE ENGINEERING

III SEMESTER

LAB MANUAL

SUBJECT: DATA STRUCTURES

SUBJECT CODE: 06CSL35

SESSION: JULY 2010 DECEMBER 2010

FACULTY: Mrs. Sarasvathi /Mrs. Pooja Agarwal / Ms. Vidya

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 1

DS LAB

Program 1
Statement of the Problem Write a C program to create a sequential file with at least five records, each record having the structure shown below: USN Name Marks1 Marks2 No-zero positive positive positive characters integer integer

Marks3 positive integer

Write necessary functions (1) To display all the records in the file. (2) To search for a specific record based on the USN. In case the required record is not found, suitable message should be displayed. Both the options in this case must be demonstrated.

Algorithm
Algorithm Display(fp) // fp is the file pointer // s is a pointer the student record while fp NULL fread(s) // read a student record Write "Student record", s end Display. Algorithm Search(fp, key) // fp is the file pointer // key - USN of the student // s is a pointer the student record while fp NULL fread(s) if USN = key Write "Here is your output of the Search:" Write USN, Name, Marks1, Marks2, Marks3 return Write "Student record not found" end Search.
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 2

DS LAB

Program 2
Statement of the Problem Write and demonstrate the following C functions: a) newStrCpy that does the same job as strcpy b) newStrCat that does the same job as strcat without using any library functions.

Algorithm
Algorithm newStrCpy(dst, src) // dst destination string // src string while src[i] NULL dst[i] src[i] increment I by 1 end newStrCpy. Algorithm newStrCat(dst, src) // dst destination string // src string i Length(dst) j 0 while src[i] NULL dst[i] src[i] increment i, j by 1 dst[j] NULL end newStrCat.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 3

DS LAB

Program 3
Statement of the Problem Write a C Program, which accepts the Internet Protocol (IP) address in decimal dot format (ex. 153.18.8.105) and converts it into 32-bit long integer (ex. 2568095849) using strtok library function and unions.

Algorithm
Algorithm ConvertIP(s) // s IP address in decimal dot notation // n 32-bit number of the IP address // octet array to hold 4 octets of IP address Initialize n by 0 Intialize j by 24 octet[1] SubStr(s, '.') octet[2] SubStr(s, '.') octet[3] SubStr(s, '.') octet[4] SubStr(s, '.') // get the 1st most significant octet // get the second octet // get the third octet // get the last least significant octet

for i 1 to 4 do n n + ASCII_to_Number(octet[i]) * pow(2, j) jj-8 end ConvertIP.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 4

DS LAB

Program 4
Statement of the Problem Write a C program to demonstrate the working of a stack of size N using an array. The elements of the stack may be assumed to be of type integer. The operations to be supported are: (a) Push (b) Pop (c) Display The program should print appropriate messages for stack overflow, stack underflow, and stack empty.

Algorithm
Algorithm Push(S, N, top, e) // S is a static array S[0..N - 1] // N is the maximum size of the stack // top is the stack pointer // e is the element to be pushed if top = N - 1 then Write "Stack Overflow" else top top + 1 S[top] e end Push. Algorithm Pop(S, N, top) // S is a static array S[0..N - 1] // N is the maximum size of the stack // top is the stack pointer // temp is a local variable to return the popped element if top = -1 then return -1 else temp S[top] top top - 1 return temp end Pop.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 5

DS LAB Program 5 Statement of the Problem Write a C program to convert and print a given valid parenthesized infix arithmetic expression to postfix expression. The expression consists of single character operands and the binary operators + (plus), (minus), * (multiply), and / (divide).

Algorithm
Algorithm Infix_Postfix(Infix, Postfix) // Infix - given infix expression of length N and right-padded with ')' // Postfix character array for the result // array S(0..N) and top are stack variables // x symbol being read top 0 ik0 S[top] ( while i <= N do x Infix[i] Case : ICP(x) = 8 // operand Postfix[k] x kk+1 : x = ) while S[top] '(' do // pop elements off the stack and output Postfix[k] Pop(S, top) kk+1 Pop(S, top) // delete ( if top = 0 then return. // Postfix has the result : default while ICP(x) < ISP( S[top] ) do // output stack elements Postfix[k] Pop(S, top) kk+1 Push(S, top, x) ii+1 end Infix_Postfix.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 6

DS LAB Program 6 Problem Statement: Write a C Program to evaluate a valid suffix/postfix expression using stack. Assume that the suffix/postfix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The arithmetic operators are + (add), -(subtract), * (multiply) and / (divide). Objective: A postfix expression is read as a string input and is evaluated using stack. Input expression is a combination of single digit positive operands and binary operators. Theory: Expressions:
The sequence of operators and operands that reduces to a single value after evaluation is called an expression. Expressions can be categorized into three types,

Stack:

Infix - Operator in between the operands. Ex : a+b Postfix - Operands followed by a operator. Ex : ab+ Prefix - Operator followed by operands. Ex : +ab

Stack is a special type of data structure where elements, can be added to a stack and removed from a stack only from one end. The fixed end of the stack is called is called the BOTTOM of the stack and the other end is called as the TOP of the stack.

Access system of a stack is referred to as a LIFO structure (Last-In First-Out) Main stack operations: push(Object o): inserts element pop(): removes and returns the last inserted element top(): returns the last inserted element without removing it size(): returns the number of elements stored isEmpty(): a Boolean value indicating whether no elements are stored

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 7

DS LAB

Logic for postfix evaluation : Algorithm


Scan the input

postfix expression left to right If the character x is a operand (digit) o Push it into the stack If the character is an operator (+,-,*,/) o pop two values(operands) from the stack o Perform the arithmetic operation o Push the result of the operation into the stack When all characters in postfix expression are processed, pop the final result from the stack and output it.
Step 2

Step 1

Step 3

Step 4

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 8

DS LAB

Step 5

Step 6

Step 7

Step 8

Step 9

Step 10

Step 11

Step 12

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 9

DS LAB

Step 13

Step 14

Step 15

Step 16

Step 17

Step 18

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 10

DS LAB

Step 19

Step 20

Step 21

Step 22

Step 23

Step 24

Step 25

Step 26

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 11

DS LAB
Step 27 Step 28

Step 29

Step 30

Step 31

Step 32

Program-7 Statement of the Problem Write a C program to simulate the working of a queue of integers using an array.Provide the following operations: a. Insert b. Delete
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 12

DS LAB c. Display Queue is a linear data structure in which data can be added to one end and retrieved from the other. Just like the queue of the real world, the data that goes first into the queue is the first one to be retrieved. That is why queues are sometimes called as First-In-First-Out data structure. In case of Queues; data is added to one end (known as REAR) and retrieved from the other end (known as FRONT). A few points regarding Queues: 1. Queues: It is a linear data structure; linked lists and arrays can represent it. Although representing queues with arrays have its shortcomings but due to simplicity, we will be representing queues with arrays . 2. Rear: A variable stores the index number in the array at which the new data will be added (in the queue). 3. Front: It is a variable storing the index number in the array where the data will be retrieved. Let us have look at the process of adding and retrieving data in the queue with the help of an example. Suppose we have a queue represented by an array queue [10], which is empty to start with. The values of front and rear variable upon different actions are mentioned in {}. queue [10]=EMPTY {front=-1, rear=0} add (5) -When you add an element to the queue ,increment rear variable.

Now, queue [10] = 5 {front=0, rear=1} add (10) Now, queue [10] = 5, 10 {front=0, rear=2} retrieve () [It returns 5] -When you delete an element from queue, increment front variable.

Now, queue [10] = 10 {front=1, rear=2} retrieve () [now it returns 10] Now, queue [10] is again empty {front=-1, rear=-1} In this way, a queue like a stack, can grow and shrink over time. rear as -1 and front as 0 when the Queue is empty. Algorithm
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 13

DS LAB 1. 2. 3. 4. Intialize rear=-1 and front =0. Declare integer array in global. In main function get the user options Insert opeartion Step-1: Increment the 'rear' by 1 Step-2: Check for the 'queue overflow' condition. If queue not overflowing then go to step-3 else say "queue overflow" and quit Step-3: Put the new element at the position pointed by 'rear'. 5. Delete operation Step-1: If(front>queue) then print the queue is empty else go to step-2 Step-2: Return the element pointed by front. Increment the 'front' by 1. 6. Display operation Step-1: if(front>rear) then print the queue is empty else goto step 2. Step-2:print the element from front to rear.

Program-8 Statement of the Problem: Write a C program to simulate the working of a circular queue of integers using an array.Provide the following operations: a. Insert b. Delete c. Display The regular or static queues have a very big drawback that once the queue is FULL, even though we delete few elements from the "front" and relieve some occupied space, we are not able to add anymore elements, as the "rear" has already reached the Queue's rear most position. The solution lies in a queue in which the moment "rear" reaches the Queue's watermark, the "first" element will become the queue's new "rear". As the name suggests, this Queue is not straight but circular; meaning, you got to have a structure like this -

in which, once the Queue is full the "First" element of the Queue becomes the "Rear" most element, if and only if the "Front" has moved forward; otherwise it will again be a "Queue overflow" state.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 14

DS LAB Here, as you can see, the "front" value is 0 and the "rear" value is 5. Initially, when such a queue is empty, the "front" and the "rear" values are 0 & -1 respectively; and the queue has a NULL value for all its element. Every time we add an element to the queue, the "rear" value increments by 1 till the time it reaches the upper limit of queue; after which it starts all over again from 0. Similarly, every time we delete an element from queue, the "front" value increments by 1 till the time it reaches the upper limit of queue; after which it starts all over again from 0. Algorithm: 1. Initialize front =0,rear=-1 and count =0; 2. Decalare integer array in global. 3. Algorithm for Insertion:Step-1: If count=max-1 then print the queue overflow. Step-2:get the item to be inserted from the user. Step-3 Calculate rear =(rear +1)%Size Step-4: q[rear]=item; Step-5:count=count+1; Algorithm for deletion:Step-1: If the count=0 then say "empty queue" and quit; else continue Step-2: Delete the "front" element Step-3: (front=front+1) %SIZE Step-4: count=count-1 Algorithm for display Step-1:if count=0 then print queue is empty Step-2:Assign j =front Step-3:print the element from start position to count. Step-4:calculate j=(j+1)%SIZE

Program-9 Problem Statement:

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 15

DS LAB Write a C Program using dynamic variables and pointers, to construct a singly linked list consisting of the following information in each node: student id (integer), student name (character string) and semester (integer). The operations to be supported are: The insertion operation o i. At the front of a list o ii. At the back of the list o iii. At any position in the list Deleting a node based on student id. If the specified node is not present in the list an error message should be displayed. Both the options should be demonstrated. Searching a node based on student id and update the information content. If the specified node is not present in the list an error message should be displayed. Both situations should be displayed. Displaying all the nodes in the list.(Note: Only one set of operations among a, b and c with d may be asked in the examination)

Objective: In this program, define a structure consisting the following as the fields :

student id (integer) student name (character string) semester (integer) Self referential pointer ( Structure type pointer)

The above structure forms a node with data fields and a link part. The operations to be performed on the singly link list are : Insertion o At the front of a list ( Insert front ) o At the back of the list ( Delete rear ) o At any position in the list Deletion o To delete a given student information, perform a search operation based on student id on the link list. If the given student id is found then deletion is performed else a suitable error message is displayed. Search
o

Perform a search operation based on student id on the link list.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 16

DS LAB Display o The content of each node is displayed sequentially till the end of the singly link list.

Theory: Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation. Following functions are available in C for the dynamic memory allocation: Malloc (..) : Allocates memory requests size of bytes and returns a pointer to the 1st byte of allocated space Calloc (..) :Allocates space for an array of elements initializes them to zero and returns a pointer to the memory Free() :Frees previously allocated space Realloc(..) :Modifies the size of previously allocated space.

Singly Link List: The linked list is an alternative to the array when a collection of objects is to be stored. For an array, memory is allocated during compile time, where the user is not sure of the memory requirement. Instead of compile-time allocation, run-time memory allocation is better in such cases. So, a linked list can be implemented using dynamic memory allocation. An element (or node) of a linked list contains the actual data to be stored and a pointer to the next node. Recall that a pointer is simply the address in memory of the next node. Thus, a key difference from arrays is that a linked list does not have to be stored contiguously in memory.

A linked list allocates space for each element separately in its own block of memory called a "linked list element" or "node". The list gets is overall structure by using pointers to connect all its nodes together like the links in a chain. Each node contains two fields: a "data field to store the information or data as per the requirement of the user, and a "next" field which is a pointer used to link one node to the next node. Each node is allocated in the heap with a call to malloc(), so the node memory continues to exist until it is explicitly de-allocated with a call to free(). The front of the list is a pointer to the first node. The last node in the list contains a null (or zero) pointer. External pointer :

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 17

DS LAB It is an pointer variable first or head to the very first node in the linked list. It enables us to access the entire linked list. If the list is not empty then external pointer contains address of the first node in the list. If the list is empty then external pointer will have value NULL

Self referential pointer: The node clearly has two fields. The first is the data field and second is the link (pointer) to the next node of same type (the same structure type) .It holds the address of the next node. So it is called as a self referential pointer. Structure or node definition struct student{ char name[10]; int id, sem; struct student *link; // self referential pointer };

Name [10]

Data field Id

Sem

Link field struct student *link

Getnode() and freenode() functions: getnode() : A function which allocates required contiguous memory for a node and returns the beginning address of the block . Function uses malloc() function for dynamic memory allocation. If the allocation is unsuccessful getnode() will return a NULL value.

struct student *x; x= malloc (sizeof(struct student)); return x; freenode(): A function which frees the allocated memory block. free (x); Insert Functions : Insert Front: To insert a node at the beginning of a linked list

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 18

DS LAB
Step 1: Allocate memory for creating empty new node. Let the address of this node be newPtr. This can be achieved from the following statement newPtr = getnode(); Step 2: Assign the value (data items) to the data field of the new node newPtr using the statements Info (newPtr) = data link (newPtr) = NULL Step 3: Attach the link field of the new Node to point to the starting node of the linked list using the following statements , if (head == NULL) head = newPtr; else link(newPtr) = head Step 4: Set the external pointer (which was pointing to the starting node) to point to the new Node. Since newPtr points to the newly inserted node at the front of the list , head = newPtr;

Insert Rear: To insert a node at the end of a linked list Step 1: Create the new empty node from getnode() . Let address of this node will be newPtr newPtr = getnode(); Step 2: Assign the value ( item) to the data fields to the new node newPtr using the statement Info (newPtr) = items; link( newPtr) = NULL; Step 3: Attach a node to the head , if it is NULL otherwise traverse auxiliary pointer (cur) to the last node and then insert the new node after the last node

if( head == NULL ) then head = newPtr; return cur = head ; Loop until (cur->link) != NULL cur = cur -> link

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 19

DS LAB

cur

Insert At The given Position: To insert a node at the given position of a linked list Step 1: Create the new empty node from getnode() . Let address of this node will be newPtr newPtr = getnode(); Step 2: Assign the value ( item) to the data fields to the new node newPtr using the statement Info (newPtr) = items; link( newPtr) = NULL; Step 3: Read the position from the user , pos Step 4: If head is empty, i.e., if list is empty and pos is equal to 1,then the new node becomes the first node of the linked list. if head == NULL && pos==1 then head = newPtr Step 5: If head is equal to NULL and pos is not equal to 1 then , If head == NULL && pos !=1 Invalid position Step 6: If pos is equal to 1 and head != NULL, then perform a insert front operation newPtr -> link = head head = newPtr Step 7: If pos is not equal to one ,then follow the below steps , Take a counter variable initialized to 1 Take two structure pointer variables as, prev = NULL and cur = head Traverse sequentially through the linked list until cur is not equal to NULL and count is not equal to pos. o Loop until cur!=NULL && count !=pos prev = cur cur=cur->link count++ If count is equal to pos then prev->link = newPtr newPtr->link = cur

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 20

DS LAB

Delete a Node At the given Position: To delete a node at the given position of a linked list based on Student ID Step 1: If head is NULL then linked list is empty. Step 2 : Take two structure pointer variables as, prev = NULL and cur = head Step 3: Read the Student Id to be deleted from the user Step 4: Traverse through the linked list until cur is not equal to NULL and cur ID is not equal to student ID Loop until cur != NULL && id !=cur->id prev = cur cur = cur->link; Step 5 :If cur is equal to NULL , then no such student exist. Stop searching Step 6: If prev is equal to NULL , then head = head -> link i.e., first node is deleted in the linked list. Stop searching

Step 7: Otherwise , a in-between deletion to be preformed prev->link = cur->link;

free(cur);

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 21

DS LAB

Search a Node in The linked list : To search a node in a linked list based on Student ID Step 1: If head is NULL then linked list is empty. Step 2 : Take one structure pointer variables as, cur = head Step 3: Read the Student Id to be deleted from the user Step 4: Traverse through the linked list until cur is not equal to NULL and cur ID is not equal to student ID Loop until cur != NULL && id !=cur->id prev = cur cur = cur->link; Step 5 :If cur is equal to NULL , then no such student exist ,display appropriate error message. Stop Searching. Step 6 :Otherwise , display the information of the node pointed by cur pointer

Display the nodes of The linked list : Step 1: If head is NULL then linked list is empty. Step 2: Take one structure pointer variables as, cur = head Step 3: Traverse through the linked list until cur is not equal to NULL and display the contents of each node Loop until cur != NULL cur = cur->link Step 4: Stop

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 22

DS LAB Program- 10

Problem Statement:
Write a C Program using dynamic variables and pointers to construct a stack of integers using singly linked list and to perform the following operations: a. Push b. Pop c. Display The program should print appropriate messages for stack overflow and stack empty.

Objective:
In this program, stack is implemented using linked list. Here, each element of the stack is implemented as a node. The linked list operations to implement stack are : Insert rear & delete rear or delete front & insert front.

Theory:
Stack is a special type of data structure where elements, can be added to a stack and removed from a stack only from one end. The fixed end of the stack is called is called the BOTTOM of the stack and the other end is called as the TOP of the stack. Access system of a stack is referred to as a LIFO structure (Last-In First-Out) Main stack operations: push(o): inserts element pop(): removes and returns the deleted element display(): To display the content of the stack

Program Logic and Algorithm:


Structure or node definition
struct node{ int info; struct node *link; // self referential pointer };

Data field Info

Link field struct node *link

Insert Front: To insert a node at the beginning of a linked list Step 1: Allocate memory for creating empty new node. Let the address of this node be newPtr. This can be achieved from the following statement newPtr = getnode(); Step 2: Assign the value (data items) to the data field of the new node newPtr using the statements

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 23

DS LAB
Info (newPtr) = data link (newPtr) = NULL Step 3: Attach the link field of the new Node to point to the starting node of the linked list using the following statements , if (head == NULL) head = newPtr; else link(newPtr) = head Step 4: Set the external pointer (which was pointing to the starting node) to point to the new Node. Since newPtr points to the newly inserted node at the front of the list , head = newPtr;

Delete Front: To delete a node at the beginning of a linked list Step 1: If head is NULL then linked list is empty. Step 2 : Take one structure pointer variables as, cur = head Step 3: To delete the front node , perform head = head -> link i.e., first node is deleted in the linked list. head = head -> link free (cur) // de-allocation of memory

Display the nodes of The linked list : Step 1: If head is NULL then linked list is empty. Step 2: Take one structure pointer variables as, cur = head Step 3: Traverse through the linked list until cur is not equal to NULL and display the contents of each node Loop until cur != NULL cur = cur->link Step 4: Stop
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 24

DS LAB

Program - 11

Problem Statement:
Write a C program using dynamic variables and pointers to construct a queue of integers using singly linked list and to perform the following operations: a. Insert b. Delete c. Display The program should print appropriate messages for queue full and queue empty.

Objective:
In this program, queue is implemented using linked list. Here, each element of the queue is implemented as a node. The linked list operations to implement queue are : Insert rear & delete front or insert front & delete rear.

Theory:
Queue is a special type of data structure where elements, can be added to a queue at one end which is called as front and removed from a queue at the other end called as rear. Access system of a queue is referred to as a FIFO structure (First-In First-Out) Main queue operations: insert(o): inserts element delete(): removes and returns the last deleted element display(): To display the content of the queue

Logic and Algorithm :


Structure or node definition
struct node{ int info; struct node *link; // self referential pointer };

Data field Info

Link field struct node *link

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 25

DS LAB

Insert Rear: To insert a node at the end of a linked list Step 1: Create the new empty node from getnode() . Let address of this node will be newPtr newPtr = getnode(); Step 2: Assign the value ( item) to the data fields to the new node newPtr using the statement Info (newPtr) = items; link( newPtr) = NULL; Step 3: Attach a node to the head , if it is NULL otherwise traverse auxiliary pointer (cur) to the last node and then insert the new node after the last node

if( head == NULL ) then head = newPtr; return cur = head ; Loop until (cur->link) != NULL cur = cur -> link

cur

Delete Front: To delete a node at the beginning of a linked list Step 1: If head is NULL then linked list is empty. Step 2 : Take one structure pointer variables as, cur = head Step 3: To delete the front node , perform head = head -> link i.e., first node is deleted in the linked list. head = head -> link free (cur) // de-allocation of memory
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 26

DS LAB

Display the nodes of The linked list : Step 1: If head is NULL then linked list is empty. Step 2: Take one structure pointer variables as, cur = head Step 3: Traverse through the linked list until cur is not equal to NULL and display the contents of each node Loop until cur != NULL cur = cur->link Step 4: Stop

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 27

DS LAB

Program-12 Statement of the Problem Write a C program to support the following opearations on a doubly linked list where each node consists of integers. a. b. c. d. Create a doubly linked list by adding each node at the front. Insert a new node to the left of the node whose key value is read as an input Delete the node of a given data,if it is found,otherwise display appropriate message. Display the contents of the list.

A doubly linked list is a linked data structure that consists of a set of data records, each having two special link fields that contain references to the previous and to the next record in the sequence. It can be viewed as two singly-linked lists formed from the same data items, in two opposite orders.

A doubly-linked list whose nodes contain three fields: an integer value, the link to the next node, and the link to the previous node. The two links allow walking along the list in either direction with equal ease. Compared to a singly-linked list, modifying a doubly-linked list usually requires changing more pointers, but is sometimes simpler because there is no need to keep track of the address of the previous node. An example doubly-linked list node with one data field:

struct dllnode{ int data; struct dllnode *llink; struct dllnode *rlink; }; Adding a Node There are four steps to add a node to a doubly-linked list: Allocate memory for the new node. Determine the insertion point to be after (pCur).
CS / IS 06CSL35 - 28

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

DS LAB Point the new node to its successor and predecessor. Point the predecessor and successor to the new node.

Current node pointer (pCur) can be in one of two states: it can contain the address of a node (i.e. you are adding somewhere after the first node in the middle or at the end) it can be NULL (i.e. you are adding either to an empty list or at the beginning of the list).

Delete a node from doubly linked list Deleting a node requires that we logically remove the node from the list by changing various links and then physically deleting the node from the list (i.e., return it to the heap). Any node in the list can be deleted. Note that if the only node in the list is to be deleted, an empty list will result. In this case the head pointer will be set to NULL. To logically delete a node: First locate the node itself (pCur). Change the predecessors and succesors link fields to point each other (see example). Recycle the node using the free() function.

Algorithm for adding each node at the front 1. 2. 3. 4. 5. 6. 7. create a new node using malloc function.it returns address of the node to temp. temp->info=info; temp->llink=NULL temp->rlink=NULL; If first=NULL then first=temp . temp-.>rlink=first first->llink=temp; first=temp;

Algorithm for inserting a node to the left of the node 1. 2. 3. 4. 5. 6. 7. 8. Create a new node using malloc function.It returns address of the node to temp. temp->info=info temp->llink=NULL temp->rlink=NULL Get the left node key value from user if first= NULL print doubly linked list is empty. if lvalue=first->info, call the function insert_front start from the first node and traverse the node until the key is found.store that node address in cur 9. temp->llink=cur->llink
CS / IS 06CSL35 - 29

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

DS LAB 10. (temp->llink)->rlink=temp 11. cur->llink=temp; 12. temp->rlink=cur Algorithm for delete a node 1. 2. 3. 4. 5. 6. 7. 8. set temp=first if first=NULL print doubly linked list is empty. Get node to be deleted from the user if date=first ->info then first=temp->rlink and free the temp node, then first->llink=NULL. start from the first node and traverse until delete key is found,then temp=temp->rlink print the deleted node (temp->rlink)->llink=temp->llink (temp->llink)->rlink=temp->rlink

Algorithm for display 1. set temp=first 2. if first=NULL print list is empty 3. while(temp!=NULL) print temp->info and then temp=temp->rlink

PROGRAM-13 Statement of the Problem Write a C program a. To construct a binary search tree of integers. b. To traverse the tree using all the methods i.e.,inorder,preorder and postorder c. To display the elements in the tree. A binary search tree (BST) or ordered binary tree is a node-based binary tree data structure which has the following properties:[1]

The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees.

From the above properties it naturally follows that:

Each node (item in the tree) has a distinct key.

Generally, the information represented by each node is a record rather than a single data element. However, for sequencing purposes, nodes are compared according to their keys rather than any part of their associated records.
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 30

DS LAB The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.

Insertion
Insertion begins as a search would begin; if the root is not equal to the value, we search the left or right subtrees as before. Eventually, we will reach an external node and add the value as its right or left child, depending on the node's value. In other words, we examine the root and recursively insert the new node to the left subtree if the new value is less than the root, or the right subtree if the new value is greater than or equal to the root. tree-traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: 1. Visit the root. 2. Traverse the left subtree. 3. Traverse the right subtree. To traverse a non-empty binary tree in inorder (symmetric), perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Visit the root. 3. Traverse the right subtree. To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Traverse the right subtree. 3. Visit the root. Thus the process is most easily described through recursion. Algorithm for constructing binary search tree //Purpose: insert data object X into the Tree //Inputs: data object X (to be inserted), binary-search-tree node node //Effect: do nothing if tree already contains X;
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 31

DS LAB // otherwise, update binary search tree by adding a new node containing data object X insert(X, node){ if(node = NULL){ node = new binaryNode(X,NULL,NULL) return } if(X = node:data) return else if(X < node:data) insert(X, node:leftChild) else // X > node:data insert(X, node:rightChild) }

Inorder Tree Walk During this type of walk, we visit the root of a subtree between the left subtree visit and right subtree visit. INORDER-TREE-WALK (x) If x NIL then INORDER-TREE-WALK (left[x]) print key[x] INORDER-TREE-WALK (right[x]) It takes (n) time to walk a tree of n nodes. Note that the Binary Search Tree property allows us to print out all the elements in the Binary Search Tree in sorted order. Preorder Tree Walk In which we visit the root node before the nodes in either subtree. PREORDER-TREE-WALK (x) If x not equal NIL then PRINT key[x] PREORDER-TREE-WALK (left[x]) PREORDER-TREE-WALK (right[x])

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 32

DS LAB

Postorder Tree Walk In which we visit the root node after the nodes in its subtrees. POSTORDER-TREE-WALk (x) If x not equal NIL then POSTORDER-TREE-WALK (left[x]) PREORDER-TREE-WALK (right[x]) PRINT key [x] It takes O(n) time to walk (inorder, preorder and pastorder) a tree of n nodes.

PROGRAM-14 Statement of the Problem Write recursive C Programs for a. Searching an element on a given list of integers using the Binary Search method. b. Solving the Towers of Hanoi problem.

Searching
Algorithm 1. 2. 3. 4. 5. Get the number of elements and array elements from the user sort the array elememts using any sort. get the key elements for searching assign low=0;high=n-1 call bin function bin(int a[],int low,int high,int key) if(low<=high) { mid= (low+high)/2 if(key==a[mid])
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 33

DS LAB return mid if(key<a[mid] return(bin(a,low,mid-1,key) if(key>a[mid]) return(bin(a,mid+1,high,key)); } return(-1) } The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

Recursive solution
A key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached. The following procedure demonstrates this approach.

label the pegs A, B, Cthese labels may move at different steps let n be the total number of discs number the discs from 1 (smallest, topmost) to n (largest, bottommost)

To move n discs from peg A to peg C: 1. move n1 discs from A to B. This leaves disc #n alone on peg A 2. move disc #n from A to C 3. move n1 discs from B to C so they sit on disc #n The above is a recursive algorithm: to carry out steps 1 and 3, apply the same algorithm again for n1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This step, moving a single disc from peg A to peg B, is trivial.
PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 34

DS LAB Algorithm 1. Get no of disc from user. 2. call the function tower(n,a,b,c) 3. tower(n,source,temp,dest) { if(n==1){ print n is moved from source to destination count=count+1 return} tower(n-1,source,dest,temp); print n is moved from source to destination print count for total no of movements.

PES School of Engg. Education for the Real World Lab Manual BE III-Sem

CS / IS

06CSL35 - 35

Das könnte Ihnen auch gefallen