ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists

Similar documents
Solution for Data Structure

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

Linked List. April 2, 2007 Programming and Data Structure 1

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

The time and space are the two measure for efficiency of an algorithm.

Cpt S 122 Data Structures. Data Structures

Programming. Lists, Stacks, Queues

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

ESc101: Pointers and Arrays

3/13/2012. ESc101: Introduction to Computers and Programming Languages

CP2 Revision. theme: dynamic datatypes & data structures

MODULE V: POINTERS & PREPROCESSORS

Write a program that creates in the main function two linked lists of characters and fills them with the following values:

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

Frequently asked Data Structures Interview Questions

Assignment 6. Q1. Create a database of students using structures, where in each entry of the database will have the following fields:

.:: UNIT 4 ::. STACK AND QUEUE

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

File: /media/young/d1 (180713)/Work tive_tree_search/search_defs.h Page 1 of 1

Lecture 7: Data Structures. EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Archivo: /home/young/work/cordic/binary_tree_search/search_defs.h Página 1 de 1

Linked Lists in C and C++

C PROGRAMMING Lecture 5. 1st semester

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

Self-referential Structures and Linked List. Programming and Data Structure 1

Linked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Ashish Gupta, Data JUET, Guna

PROGRAMMAZIONE I A.A. 2017/2018

Downloaded from : Algorithm: Implementation QUESTION 1 :

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Introduction to Data Structures. Systems Programming

Procedural Programming

CT11 (ALCCS) DATA STRUCTURE THROUGH C JUN 2015

STACKS 3.1 INTRODUCTION 3.2 DEFINITION

CSE 230 Intermediate Programming in C and C++

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

Please submit your request directly to Noha Sinno

Data Structures and Algorithms for Engineers

BBM 201 DATA STRUCTURES

BITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER

CSCI 2132 Software Development. Lecture 20: Program Organization

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME

Algorithms, Data Structures, and Problem Solving

DC104 DATA STRUCTURE JUNE Q.2 a. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

What is recursion. WAP to find sum of n natural numbers using recursion (5)

Data Structures and Algorithms for Engineers

BBM 201 DATA STRUCTURES

JTSK Programming in C II C-Lab II. Lecture 3 & 4

COP 3502 Section 2 Exam #2 Version A Spring /23/2017

Module III. Linear Data Structures and their Linked Storage Representation

CS 241 Data Organization Binary Trees

a) State the need of data structure. Write the operations performed using data structures.

Lists, Stacks and Queues in C. CHAN Hou Pong, Ken CSCI2100A Data Structures Tutorial 4

Dynamic Data Structures

CSC 1600 Memory Layout for Unix Processes"

1 P age DS & OOPS / UNIT II

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

CMSC Introduction to Algorithms Spring 2012 Lecture 7

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

ECE264 Fall 2013 Exam 3, November 20, 2013

Introduction to Data Structures and Algorithms

Data Structure & Algorithms Laboratory Manual (CS 392)

15. Stacks and Queues

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Data Abstractions. National Chiao Tung University Chun-Jen Tsai 05/23/2012

Fundamentals of Programming & Procedural Programming

Postfix (and prefix) notation

List, Stack and Queue Implementation

Information Science 2

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

Outline. Computer programming. Usage of time and date functions. Date and Time: time.h. Date and Time: time.h. Time functions:

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Programming in C. Lecture Tiina Niklander. Faculty of Science

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified) WINTER 16 EXAMINATION Model Answer Subject Code:

Linked Lists and other Dynamic Data Structures

Computer programming. "An expert is a man who has made all the mistakes which can be made, in a narrow field." Niels Bohr

malloc(), calloc(), realloc(), and free()

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #13

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

3. Fundamental Data Structures

LINKED LIST IMPLEMENTATION USING C LANGUAGE: A REVIEW

CS 216 Exam 1 Fall SOLUTION

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39

C Language Part 3. Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Archivo: /home/young/work/cordic/mvr_exhaustive.c Página 1 de 6

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

Transcription:

ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees Instructor: Krithika Venkataramani Semester 2, 2011-2012 1 Introduction to Linked Lists Each bead connected to the next through a link Can change the order of the beads by changing the link/connection Bead ~ Data Linked beads ~ Linked list of data Changing links is useful in sorting Need not use additional temporary spaces as in array sorting 2 1

Uses and Operations on Linked Lists Linear linked list: last element is not connected to anything Circular linked list: last element is connected to the first Dynamic: Size of a linked list grows or shrinks during the execution of a program and is just right Advantage: It provides flexibility in inserting and deleting elements by just re-arranging the links Disadvantage: Accessing a particular element is not easy There are three major operations on linked lists 1 Insertion 2 Deletion 3 Searching 3 Structure for an element of the linked list A linked list contains a list of data The Data can be anything: number, character, array, structure, etc. Each element of the list must also link with the next element Therefore, a structure containing data and link is created The link is a pointer to the same type of structure struct Node int data ; struct Node *next ; ; This is called a self-referential pointer 4 2

Linked list: chain of nodes A linked list is simply a linear chain of such nodes The beginning of the list is maintained as a pointer to the first element (generally called head) Space for an element is created using a pointer (say q) q = (struct Node *) malloc (size of (struct Node) ); q->data is the desired value q->next is NULL A list element s members are accessed using the pointer (q) to the list element data using q->data next element pointer using q->next Moving to next element is done using pointers q = q next; 5 head Recap of Linear Linked Lists Each element: data + link (pointer to next element) Element is also called a node Head: address of first element Last element pointer: NULL All operations done using pointers Allocation of space of element Assigning and accessing data values Moving to next element data next data next data next NULL 6 3

Linked List: element definition and creation #include <stdio.h> #include <stdlib.h> typedef struct Node int data; // data of a node: list is made of these elements struct Node *next; // link to the next node node; node *create_node(int val) node *n; n = malloc(sizeof(node)); n->data = val; n->next = NULL; return n; 7 Sample Linked List creation 0.... 200 25 p1 10 100 204 NULL head 18 100 p2 26 130 end 34 130 200 p3 42 200 100 15 104 NULL 130 --- 130 20 NULL 200 --- node: int + pointer node *p1, *head, *p2, *end, *p3; p1 = create_node(15); head = p1; p2 = create_node(20); /*insert at end*/ head->next = p2; end = head->next; p3 = create_node(25); end->next = p3; end = end->next; 8 4

Insertion at the beginning of the list Create a new node (say q) Make q->next point to head Make head equal to q If list is empty, i.e., head is NULL Make head equal to q 9 Insertion at end of list Create a new node (say q) Find the last element (say p) Mk Make p->next point to q If list is empty, i.e., head is NULL Make head equal to q 10 5

Deletion at the beginning of the list Make p equal to head Make head equal to head->next Delete p (by using free) If list is empty, i.e., head is NULL Nothing to do If list contains only one element Delete head head is now NULL 11 Deletion from the end of the list Find the last element (say p) While finding p, maintain q that points to p q is the node just before p, i.e., q->next is p Make q->next NULL Delete p (by using free) If list is empty, i.e., head is NULL Nothing to do If list contains only one element Delete head head is now NULL 12 6

Searching a node (insert after, delete after) Make p equal to head While p->data not equal to the data that is being searched, make p equal to p->next Using search, insert after and delete after operations can be implemented Insert after p Create a new node q Make q->next equal to p->next Make p->next equal to q Delete after p Call the next node, i.e., p->next as q Make p->next equal to q->next Delete q 13 Linked List: element definition and creation #include <stdio.h> #include <stdlib.h> typedef struct Node int data; // data of a node: list is made of these elements struct Node *next; // link to the next node node; node *create_node(int val) node *n; n = malloc(sizeof(node)); n->data = val; n->next = NULL; return n; 14 7

Displaying the data in the linked list void print_list(node *h) /*Display data in each element of the linked list*/ node *p; p = h; while (p!= NULL) printf("%d --> ", p->data); p = p->next; 15 Inserting at end int main() node *head = NULL; // head maintains the entry to the list node *p = NULL, *q = NULL; int v = -1, a; printf("inserting at end: Enter the data value:\n"); scanf("%d", &v); while (v!= -1) q = create_node(v); if (head == NULL) head = q; 16 8

Inserting at end (cont.) else /*non empty list*/ p = head; while (p->next!= NULL) p = p->next; p->next = q; scanf("%d", &v); print_list(head); /*Display the data in the list*/ 17 Inserting at the beginning printf("inserting at beginning\n"); scanf("%d", &v); while (v!= -1) q = create_node(v); q->next = head; head = q; scanf("%d", &v); print_list(head); /*Display the data in the list*/ 18 9

printf("inserting after\n"); scanf("%d", &v); while (v!= -1) q = create_node(v); scanf("%d", &a); p = head; while ((p!= NULL) && (p->data!= a)) p = p->next; if (p!= NULL) q->next = p->next; p->next = q; scanf("%d", &v); print_list(head); /*Display the data in the list*/ Inserting after an element 19 Deleting from the end printf("deleting from end\n"); if (head!= NULL) p = head; while (p->next!= NULL) q = p; p = p->next; q->next = NULL; free(p); print_list(head); /*Display the data in the list*/ 20 10

Deleting from the beginning printf("deleting from beginning\n"); if (head!= NULL) p = head; head = head->next; free(p); /*Empty list: i.e. head==null, do nothing*/ print_list(head); /*Display the data in the list*/ 21 Deleting after an element printf("deleting after\n"); scanf("%d", &a); p = head; while ((p!= NULL) && (p->data!= a)) p = p->next; if (p!= NULL) q = p->next; if (q!= NULL) p->next = q->next; free(q); print_list(head); /*Display the data in the list*/ 22 11

Stacks and Queues The linked list only allows for sequential traversal Sequential traversal is present in stacks and queues Linked lists are used to implement these Stack Queue 23 Stacks Insert at top of stack and remove from top of stack Stack operations also called Last-In First-Out (LIFO) Stack Operations: Push and Pop Push: insert at the top/beginning of stack Pop: delete from the top/beginning of stack 24 12

Conversion of Decimal number to Binary Convert decimal number 39 to binary 39/2 = 19 +1 19/2 = 9 +1 9/2 = 4 +1 4/2 = 2 +0 2/2 = 1 +0 1/2 = 0 +1 Read remainder from bottom to top Binary representation: 100111 Stack can be used to read remainders in correct order 25 Stack Push Operations: Decimal to Binary Address Values 1000 Head = 200 2 6 3 0 200 0 [rem(6/2)] head = NULL; push(&head,0); 2 1 0 1 push(&head,1); 204 NULL 1000 Head = 270 270 1 [rem(1/2)] 274 250 250 1 [rem(3/2)] 254 200 2 3 1 1 push(&head,1); 1000 Head = 250 250 1 [rem(3/2)] 254 200 200 0 [rem(6/2)] 204 NULL 200 0 [rem(6/2)] 204 NULL 26 13

Stack Push stack top/head has the address of the first element Function needs the address to the stack top/head to make changes to head void push(node **head_address, int top) node *q; q = create_node(top); /*New element storing the new data*/ q->next = *head_address; address; /*New element pointing to head*/ *head_address = q; /*head pointing to new element*/ return; 27 Stack pop operations: Decimal to Binary Head = 270 270 1 [rem(1/2)] 274 250 250 1 [rem(3/2)] 254 200 200 0 [rem(6/2)] 204 NULL rem= pop(&head); printf( %d, rem); 11 rem= pop(&head); printf( %d, rem); 1 Head = 200 200 0 [rem(6/2)] 204 NULL Head = 250 250 1 [rem(3/2)] 254 200 200 0 [rem(6/2)] 204 NULL rem= pop(&head); printf( %d, rem); 110 Head = NULL 28 14

int pop(node **head_address) Stack Pop node *p, *head; int top; head = *head_address; /*head has address of the first element*/ if (head!= NULL) p = head; //p: address of stack top element in stack top = p->data; //data in stack top/first element head = head->next; //head now has address of 2 nd element in stack free(p); //remove the first element in stack else top = -1; //-1 denotes invalid value or empty list *head_address = head; /*reflect the changes to head outside*/ return top; 29 Stack operations: Decimal to Binary void main() node *head = NULL; // head: address of stack top or stack reference int decimal, rem, binary[20], j=0; printf("enter the (positive) decimal value:"); scanf("%d",&decimal); /*Push: store binary digits in correct order*/ while(decimal>0) rem = decimal%2; push(&head,rem); decimal = decimal/2; 30 15

Stack operations: Decimal to Binary (cont.) /*Pop : to read binary digits in correct order*/ printf("binary representation: "); while(head!=null) rem = pop(&head); printf("%d",rem); binary[j]=rem; j++; printf("\n"); binary[j]= -1; //to denote end of binary representation 31 Queues Queue operations are also called First-in first-out Operations Enqueue: insert at the end of queue Dequeue: delete from the beginning of queue Code: similar to previous code on linked lists Queue Application: Executing processes by operating system Operating System puts new processes at the end of a queue System executes processes at the beginning of the queue 32 16

Circular Lists The last element of a linked list points to the first element. A reference pointer is required to access the list: head head data next data next data next 33 Circular Lists The list pointer can have the address of the last element. The tail/last element can be accessed by the list pointer The head/first element can be accessed from the tail/last t element (by list->next) Provides flexibility in accessing first and last elements Circular lists can be used for queues. Useful in enqueue/dequeue operations without needing to traverse the list list data next data next data next 34 17

Queue using a circular list Enqueue: insertion at the end of the list The list pointer to the last element is known Insert new element using this Dequeue: deletion at the beginning of the list Traversing one element from the list pointer (to the last element) gives the first element Traversal of the entire list need not be done The list needs to be checked if it is empty 35 Create an element in the queue struct Node //list element char *name; // data of an element in the list struct tnode *next; // reference to the next element ; struct Node *create_node(char *Name) //create a list element struct Node *n; n = malloc(sizeof(struct Node)); //create space for the element n->name = (char *)malloc((strlen(name)+1)*sizeof(char)); sizeof(char)); /*create space for name*/ strcpy(n->name,name); n->next = NULL; return n; 36 18

void print_list(struct Node *h) Print list of elements in queue struct Node *p; p = h; if (p==null) //no element in list printf("\nno elements in the queue"); return; printf("queue elements"); p = p->next; //first element in the list while (p!=h) //while last element has not been reached printf("\n%s", p->name); p = p->next; printf("\n%s", p->name); //print last element 37 struct Node* enqueue(struct Node *list, char *Name) Enqueue: Add to the end of the queue struct Node *n; n = create_node(name); // create new element if (list==null) // if no element in the queue list = n; list->next = list; else //list points to the last element in queue n->next = list->next; //give reference to first element from new element list->next = n; // add the new element to the end of queue list = n; //provide reference to the end of the queue return(list); 38 19

Dequeue: Remove element from queue end struct Node* dequeue(struct Node *list) struct Node *temp; if (list==null) //error check printf("\nerror: No elements in queue to dequeue"); else if (list->next==list) //only one node free(list); //return memory to system list = NULL; else return(list); temp = list->next; //first node list->next = list->next->next; //remove the link to the first node free(temp); //return memory of the deleted first node to the system 39 Calling different queue operations void main() struct Node *list = NULL; // address of the last element in the circular list char command, Name[50]; scanf(" %c", &command); //read queue operation while ((command!='s') && (command!='s')) //Stop operations: S if ((command=='e') (command=='e')) //Enqueue: E <name> scanf(" %s", Name); list = enqueue(list, Name); else if ((command=='d') (command=='d')) //Dequeue: D list = dequeue(list); else if ((command=='l') (command=='l')) //Print queue: L print_list(list); 40 20

Calling different queue operations (cont.) else //error check printf("incorrect operation"); printf("\nenter another queue operation: "); scanf(" %c", &command); 41 Josephus problem A set of players are present in a circle Counting from a given player, every nth player is considered out and eliminated from the game Counting starts again from the next person after the removed player, and the next nth player is removed. The game continues until only one player remains, who is the winner 42 21

Algorithm for Josephus Problem 1. Obtain the initial player list 2. Go to starting player. Start count of 1. 3. Increment count, go to next player. If player-list list end is reached, go to list beginning. 4. If count < n, go back to step 3 5. If count = n, remove player from list. Set count = 1 from next player. Go back to Step 3. 6. If next player is same as current player, declare winner. Implementation 2D Arrays to hold player names Circular lists Circular lists are an easier implementation for Step 3 Step 5: easier with doubly linked circular lists workaround: eliminate nth player when count = n-1 43 Josephus Problem with n = 3, starting from 1 Start counting from this 1 person list Pointer to the circular 6 2 list at the 5 beginning gof 3 the game 4 3: Out of game : To be deleted List pointer: to the end of list 44 22

Josephus Problem with n = 3, starting from 1 (cont.) 6: Out of game: to be deleted 1 6 2 list Start counting from this person 5 4 3 45 Josephus Problem with n = 3, starting from 1 (cont.) 1 Start counting from this person 6 2 list 5 3 4 4: Out of game : To be deleted 46 23

Josephus Problem with n = 3, starting from 1 (cont.) 1 6 2 list 2: Out of game : To be deleted Start counting from this person 5 4 3 47 Josephus Problem with n = 3, starting from 1 (cont.) 1 list 1: is the winner 6 2 Start counting from this person 5 4 3 5: Out of game : To be deleted 48 24

Create an element in the list struct Node //list element char *name; // data of an element in the list struct tnode *next; // reference to the next element ; struct Node *create_node(char *Name) //create a list element struct Node *n; n = malloc(sizeof(struct Node)); //create space for the element n->name = (char *)malloc((strlen(name)+1)*sizeof(char)); sizeof(char)); /*create space for name*/ strcpy(n->name,name); n->next = NULL; return n; 49 struct Node* enqueue(struct Node *list, char *Name) Enqueue: Add to the end of the list struct Node *n; n = create_node(name); // create new element if (list==null) // if no element in the queue list = n; list->next = list; else //list points to the last element in queue n->next = list->next; //give reference to first element from new element list->next = n; // add the new element to the end of queue list = n; //provide reference to the end of the queue return(list); 50 25

Dequeue: Remove element from queue beginning struct Node* dequeue(struct Node *list) struct Node *temp; if (list==null) //error check printf("\nerror: No elements in queue to dequeue"); else if (list->next==list) //only one node free(list); //return memory to system list = NULL; else return(list); temp = list->next; //first node list->next = list->next->next; //remove the link to the first node free(temp); //return memory of the deleted first node to the system 51 Josephus problem code void josephus() char Name[50], *end = "end"; struct Node *list = NULL; // 'Node data has player name. 'list' points to end of the list int n, i; printf("\nenter list of player names\n"); scanf(" %s", Name); while (strcmp(name,end)!=0) /*create the list of players, reading names until "end"*/ list = enqueue(list, Name); /*same enqueue function as before to create list*/ scanf(" %s", Name); printf("enter the count of the next player eliminated: "); scanf("%d",&n); //nth player eliminated 52 26

Eliminating players printf("order of players eliminated from game"); /* Play the game by starting count from list beginning*/ while (list!=list->next) // while more than one player is left, continue game for (i=1; i < n; i++) list = list->next; printf("\n%s",list->next->name); // name of the player eliminated from the game list = dequeue(list); //same dequeue function as before printf("the winner of the game is: %s", list->name); 53 Doubly linked lists Linked list disadvantages Cannot traverse the list backwards Cannot delete an element using only a pointer to that element Doubly linked lists: pointers to next element as well as previous element Use previous element pointer for given node deletion Pointers to both ends of the lists are stored head: beginning of list Tail tail: end of list Head Data 15 Previous Next NULL 250 address: 200 Data 20 Previous Next 200 300 address: 250 Data 25 Previous Next 250 NULL address: 300 54 27

Doubly linked lists: applications Queue implementation with doubly linked lists Enqueue: insertion at Queue end (using tail ) Dequeue: deletion at Queue begin (using head) Addition of long integers through doubly linked lists Traverse from list end while adding Traverse from list beginning to display 55 Doubly Linked List: element definition typedef struct Node /*Element definition*/ int data; struct node *previous; struct node *next; node; node *head = NULL; node *tail = NULL; node *s; /*Creating first node*/ s = (node *) malloc (sizeof (node)); s->data = 15; s->previous = NULL; s->next = NULL; head = s; tail = s; 56 28

Removing an element printf("deleting a given element\n"); scanf("%d", &a); /*enter the data to be deleted*/ p = head; while ((p!= NULL) && (p->data!= a)) /*searching the data to be deleted*/ p = p->next; if (p!= NULL) /*p is the node to be deleted*/ if (p->previous == NULL) /*if p is head*/ head = head->next; /*move head to next element*/ head->previous = NULL: 57 Removing an element (cont.) else if (p->next == NULL) /*if p is tail*/ tail = tail->previous; /*move tail to previous element*/ tail->next = NULL; else /*p is in the middle of the list*/ (p->previous)->next = p->next; (p->next)->previous = p->previous; free(p); //deleting the node p /*end of if statement*/ print_list(head); 58 29

Inserting after a given element Will not change head May change tail, if the given element (n) is the last element q = create_node(v); //new node q scanf("%d", &a); //enter data value, a, to be searched for p = head; while ((p!= NULL) && (p->data!= a)) //a is being searched for p = p->next; if (p!= NULL) //new node q is inserted after p q->previous = p; q->next = p->next; if (p->next==null) //if p is tail tail = q; //q becomes new tail else (p->next)->previous = q; p->next = q; 59 Binary Trees Searching is more efficient in a binary tree than from an array Binary search can be easily understood using binary trees Searching starts from the top/root of the binary search trees Search stops if the number, n, is found in the node If n < the number stored in the node, searching is done from the left child If n > the number stored in the node, searching is done from the right child The procedure is continued till the number is found. 60 30

Binary Tree Creation A binary tree can be created from an array One approach: Use the first element as the root node, R. If the 2nd element is less (greater) than the root, insert it as a left (right) child, C If the 3rd element is less(greater) than the root, traverse to the left (right) child, C, of root node If the 3 rd element is less (greater) than this child node, insert it as a left (right) child to C. Repeat this process for every element in the array If the array is sorted, this approach will lead to an unbalanced tree 61 Binary Tree Creation 1 5 3 2 4 Array L 1 R Root Null 5 L R 3 Null L R 2 4 L R L R Null Null Null Null 62 31

The content of some of these slides are from the lecture slides of Prof. Arnab Bhattacharya and Prof. Dheeraj Sanghi 63 32