Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to C Programming CE00312-1 Lecture 22 Recursive Functions for Insertion and Deletion in Linear Linked Lists.

Similar presentations


Presentation on theme: "Introduction to C Programming CE00312-1 Lecture 22 Recursive Functions for Insertion and Deletion in Linear Linked Lists."— Presentation transcript:

1 Introduction to C Programming CE00312-1 Lecture 22 Recursive Functions for Insertion and Deletion in Linear Linked Lists

2 Insertion into a linear Linked List As pointer, list, moves recursively DOWN the list, insert new node when its data < list node’s value., i.e. 7 < 8, and return pointer, new. As we return BACK up the list, link in the returned pointer. 35812 - 7 new list

3 Design of Recursive Insert CASE 1:Empty list data = 50 Givenlist == NULL Returnnew 50 NULL

4 CASE 2:Insert BEFORE node data = 40 Givendata value list Returnnew 50 40

5 CASE 3:Insert LATER data = 60 Givendata >= list->value list Returnlist 50 Link in from Insert 60

6 Recursive insert function Listpointer insert(int data, Listpointer list) { Listpointer new; if (list == NULL || data value) { //CASE 1 & 2 new = (Listpointer)malloc(sizeof(struct node)); new -> value = data; new -> next = list; return new; // new node } else// CASE 3 { list -> next = insert(data, list->next); return list; // insert data later and return list }

7 Deletion from an ascending Linear Linked List Pointer, list, moves down the list recursively, when the data is found, e.g. 8, the link to the next node is returned to the previous, and linked in as we return back up the list. Actually the next node is also checked for multiple occurrences. Should the data not occur in the list, e.g. 6, then pointer, list, is returned. 35812 - list

8 Design of recursive delete CASE 1: Empty listReturn empty list CASE 2: data = 50 found data == list -> value Given list Returnp 50 60

9 CASE 3: gone too far, data = 60 list->value > data list Returnlist CASE 4: further to go, data = 80 list->value < data Given return 70 list link new pointer 70 80 90

10 Recursive delete function Listpointer delete(int data, Listpointer list) {// delete ALL occurrences in ASCENDING list Listpointer p; if (list == NULL) return NULL; // CASE 1 else if (list -> value == data) { // CASE 2 p = delete(data, list -> next); // delete more occurrences free (list); // free this node return p; // return rest of list }

11 else if (list -> value > data) { // CASE 3 data was earlier return list; } else// data later in list { // CASE 4 list -> next = delete_item(data, list -> next); // check rest return list; }


Download ppt "Introduction to C Programming CE00312-1 Lecture 22 Recursive Functions for Insertion and Deletion in Linear Linked Lists."

Similar presentations


Ads by Google