ds lab final

Upload: vikram360

Post on 06-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Ds Lab Final

    1/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 1

    PES SCHOOL OF ENGINEERING1Km 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

  • 8/3/2019 Ds Lab Final

    2/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 2

    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 Marks3

    No-zero positivecharacters

    positiveinteger

    positiveinteger

    positiveinteger

    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 recordis 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 recordWrite "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

    returnWrite "Student record not found"

    end Search.

  • 8/3/2019 Ds Lab Final

    3/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 3

    Program 2Statement of the Problem

    Write and demonstrate the following C functions:

    a) newStrCpy that does the same job as strcpyb) 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] NULLdst[i] src[i]

    increment I by 1end newStrCpy.

    Algorithm newStrCat(dst, src)

    // dst destination string

    // src stringi Length(dst)

    j 0

    while src[i] NULLdst[i] src[i]increment i, j by 1

    dst[j] NULL

    end newStrCat.

  • 8/3/2019 Ds Lab Final

    4/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 4

    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 andunions.

    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 0Intialize j by 24

    octet[1] SubStr(s, '.') // get the 1st most significant octetoctet[2] SubStr(s, '.') // get the second octet

    octet[3] SubStr(s, '.') // get the third octet

    octet[4] SubStr(s, '.') // get the last least significant octet

    for i 1 to 4 don n + ASCII_to_Number(octet[i]) * pow(2, j)j j - 8

    end ConvertIP.

  • 8/3/2019 Ds Lab Final

    5/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 5

    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 elementif top = -1

    then return -1else

    temp S[top]

    top top - 1

    return tempend Pop.

  • 8/3/2019 Ds Lab Final

    6/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 6

    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

    i k 0

    S[top] (

    while i

  • 8/3/2019 Ds Lab Final

    7/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 7

    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 arithmeticoperators. 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 anexpression. Expressions can be categorized into three types,

    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:

    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 otherend 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

  • 8/3/2019 Ds Lab Final

    8/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 8

    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 stacko Perform the arithmetic operationo Push the result of the operation into the stack

    When all characters in postfix expression are processed, pop the final result from the stack andoutput it.

    Step 1 Step 2

    Step 3 Step 4

  • 8/3/2019 Ds Lab Final

    9/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 9

    Step 5 Step 6

    Step 7 Step 8

    Step 9 Step 10

    Step 11 Step 12

  • 8/3/2019 Ds Lab Final

    10/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 10

    Step 13 Step 14

    Step 15 Step 16

    Step 17 Step 18

  • 8/3/2019 Ds Lab Final

    11/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 11

    Step 19 Step 20

    Step 21 Step 22

    Step 23 Step 24

    Step 25 Step 26

  • 8/3/2019 Ds Lab Final

    12/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 12

    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. Insertb. Delete

  • 8/3/2019 Ds Lab Final

    13/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 13

    c. DisplayQueue 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 asFRONT).

    A few points regarding Queues:

    1. Queues: It is a linear data structure; linked lists and arrays can represent it. Although representingqueues 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 thequeue).

    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 offront 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

  • 8/3/2019 Ds Lab Final

    14/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 14

    1. Intialize rear=-1 and front =0.2. Declare integer array in global.3. In main function get the user options4. 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 elsesay "queue overflow" and quit

    Step-3: Put the new element at the position pointed by 'rear'.

    5. Delete operationStep-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. Insertb. Deletec. DisplayThe 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 inwhich 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 Queuebecomes the "Rear" most element, if and only if the "Front" has moved forward; otherwise it will again be

    a "Queue overflow" state.

  • 8/3/2019 Ds Lab Final

    15/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 15

    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" valueincrements 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 itreaches 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:

  • 8/3/2019 Ds Lab Final

    16/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 16

    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 operationo i. At the front of a listo ii. At the back of the listo 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 errormessage should be displayed. Both the options should be demonstrated.

    Searching a node based on student id and update the information content. If the specifiednode 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 dmay 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 :

    Insertiono At the front of a list ( Insert front ) o At the back of the list ( Delete rear )o At any position in the list

    Deletiono To delete a given student information, perform a search operation based on student idon the link list. If the given student id is found then deletion is performed else a

    suitable error message is displayed.

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

  • 8/3/2019 Ds Lab Final

    17/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 17

    Displayo 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 ofallocated space

    Calloc (..) :Allocates space for an array of elements initializes them to zero and returns apointer 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 listelement" or "node". The list gets is overall structure by using pointers to connect all its nodes together

    the links in a chain. Each node contains two fields: a"data field to store the information or data as per threquirement of the user, and a "next" field which is a pointer used to link one node to the next node. Each allocated in the heap with a call to malloc(), so the node memory continues to exist until it is explicitly de-allo

    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 (

    zero) pointer.

    External pointer :

  • 8/3/2019 Ds Lab Final

    18/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 18

    It is an pointer variable first or head to the very first node in the linked list. It enables us to access the entirlinked 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 s

    type (the same structure type) .It holds the address of the next node. So it is called as a self referential point

    Structure or node definition

    struct student{

    char name[10];

    int id, sem;

    struct student *link; // self referential pointer

    };

    Data field Link field

    Name [10 Id Sem struct student *link

    Getnode() and freenode() functions:

    getnode() : A function which allocates required contiguous memory for a node and returns the beginning ad

    of the block . Function uses malloc() function for dynamic memory allocation. If the allocation is unsuccessfu

    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

  • 8/3/2019 Ds Lab Final

    19/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 19

    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 newPtrusing 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

    newPtrpoints 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

  • 8/3/2019 Ds Lab Final

    20/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 20

    nsert 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 !=1Invalid 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!=NULLcount !=pos

    prev = curcur=cur->link

    count++

    If count is equal to pos thenprev->link = newPtr

    newPtr->link = cur

    cur

  • 8/3/2019 Ds Lab Final

    21/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 21

    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);

  • 8/3/2019 Ds Lab Final

    22/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 22

    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 IDLoop 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

  • 8/3/2019 Ds Lab Final

    23/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 23

    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 followi

    operations:

    a. Pushb. 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 operation

    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 estack 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 Link field

    Info 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 newPtrusing the statements

  • 8/3/2019 Ds Lab Final

    24/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 24

    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

    newPtrpoints 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

  • 8/3/2019 Ds Lab Final

    25/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 25

    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 follow

    operations:

    a. Insert

    b. Deletec. 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 operati

    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 q

    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 Link field

    Info struct node *link

  • 8/3/2019 Ds Lab Final

    26/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 26

    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

    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

    cur

  • 8/3/2019 Ds Lab Final

    27/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 27

    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

  • 8/3/2019 Ds Lab Final

    28/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 28

    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. Create a doubly linked list by adding each node at the front.b. Insert a new node to the left of the node whose key value is read as an inputc. Delete the node of a given data,if it is found,otherwise display appropriate message.d. 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 twospecial linkfields that contain references to the previous and to the next record in the sequence. It can beviewed 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-linkedlist, modifying a doubly-linked list usually requires changing more pointers, but is sometimes simplerbecause 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).

  • 8/3/2019 Ds Lab Final

    29/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 29

    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 themiddle 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 linksand 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 emptylist 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. create a new node using malloc function.it returns address of the node to temp.2.

    temp->info=info;3. temp->llink=NULL

    4. temp->rlink=NULL;5. If first=NULL then first=temp .6. temp-.>rlink=first7. first->llink=temp; first=temp;

    Algorithm for inserting a node to the left of the node

    1. Create a new node using malloc function.It returns address of the node to temp.2. temp->info=info3.

    temp->llink=NULL4. temp->rlink=NULL

    5. Get the left node key value from user6. if first= NULL print doubly linked list is empty.7. if lvalue=first->info, call the function insert_front8. start from the first node and traverse the node until the key is found.store that node address in

    cur9. temp->llink=cur->llink

  • 8/3/2019 Ds Lab Final

    30/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 30

    10.(temp->llink)->rlink=temp11.cur->llink=temp;12.temp->rlink=cur

    Algorithm for delete a node

    1. set temp=first2. if first=NULL print doubly linked list is empty.3. Get node to be deleted from the user4. if date=first ->info then first=temp->rlink and free the temp node, then first->llink=NULL.5. start from the first node and traverse until delete key is found,then temp=temp->rlink6. print the deleted node7. (temp->rlink)->llink=temp->llink8. (temp->llink)->rlink=temp->rlink

    Algorithm for display

    1. set temp=first2. if first=NULL print list is empty3. while(temp!=NULL) print temp->info and then temp=temp->rlink

    PROGRAM-13

    Statement of the Problem

    Write a C programa. To construct a binary search tree of integers.b. To traverse the tree using all the methods i.e.,inorder,preorder and postorderc. 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 oftheir associated records.

  • 8/3/2019 Ds Lab Final

    31/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 31

    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 assets, 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 newnode 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 eachnode, 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 ateach 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 objectX(to be inserted), binary-search-tree node node

    //Effect: do nothing if tree already containsX;

  • 8/3/2019 Ds Lab Final

    32/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 32

    // 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)

    returnelse if(X < node:data)

    insert(X, node:leftChild)

    else //X > node:datainsert(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)Ifx 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])

  • 8/3/2019 Ds Lab Final

    33/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 33

    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 ofn nodes.

    PROGRAM-14Statement 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. Get the number of elements and array elements from the user2. sort the array elememts using any sort.3. get the key elements for searching4. assign low=0;high=n-15. call bin function

    bin(int a[],int low,int high,int key)

    if(low

  • 8/3/2019 Ds Lab Final

    34/35

    DS LAB

    PES School of Engg. Education for the Real World Lab Manual BE III-Sem CS / IS 06CSL35 - 34

    return mid

    if(keya[mid])

    return(bin(a,mid+1,high,key));

    }

    return(-1)

    }

    The Tower of Hanoi or Towers ofHanoi is a mathematical game or puzzle. It consists of three rods, anda 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 untila 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 A2. move disc #n from A to C3. 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.

  • 8/3/2019 Ds Lab Final

    35/35

    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.

    }