90 likes | 124 Views
Learn how to tackle difficulties in deleting elements in computer programming by utilizing double linked lists for efficient traversal and management.
E N D
Computer Programming forEngineering Applications ECE 175 Intro to Programming
Difficulty in Deleting an Element headp Once we are at a node in the list, there is no mechanism to refer to the previous node, and/or start traversing the link backwards!! Solution: Double Linked Lists name age listp name age listp name age listp NULL temp ECE 175, Spring 2009
Double Linked Lists – A Link Node typedefstructnode_s { char name[20]; int age; structnode_s *leftp, *rightp; } node_t; leftp name age rightp ECE 175, Spring 2009
Double Linked Lists Can traverse the list forward or backwards Can insert an element anywhere referring to the left or right pointers Much easier to erase an element from the list headl headr node node node node node NULL NULL ECE 175, Spring 2009
voidadd_member(node_t *p, node_t **hl, node_t **hr){ node_t *temp; // pointer to a node_t temp = (node_t *)malloc(sizeof (node_t)); // new node creation printf("What is the name of the new member?:"); scanf("%s", temp->name); printf("Whatis the age?:"); fflush(stdin); scanf("%d",&temp->age); if (*hl == NULL) // if left head is null, i.e., list is empty { temp->rightp= NULL; temp->leftp = NULL; *hl = temp; *hr = temp; } elseif (p->rightp == NULL) // if adding at the end of list { temp->leftp = p; p->rightp = temp; temp->rightp = NULL; *hr = temp; } else // if adding to the middle of the list { temp->rightp = p->rightp; temp->leftp = p; p->rightp= temp; temp->rightp->leftp= temp; } } ECE 175, Spring 2009
Calling the add_member Function while(i!=0) { printf("Press 1 to add a new database element or 0 to quit>"); scanf("%d", &i); if(i != 0) { temp = headr; // address of list element before the insertion of new element add_member(temp, &headl, &headr); // function call for addition } } ECE 175, Spring 2009
Printing the List Just choose a head pointer and traverse the list voidprint_list(node_t *headl) { while (headl!=NULL) { printf("%s, %d\n", headl->name, headl->age); headl=headl->rightp; } } print_list(headl) ECE 175, Spring 2009
Deleting an Element from a Double Linked List Make rightp point to the next element Make leftp point to the previous element Reconnect headl, headr, if first or last element was deleted. voiddelete_member(node_t *p, node_t **hl, node_t **hr) { if (p == *hl) // if deleting the first element *hl=p->rightp; // update the left headp else p->leftp->rightp = p->rightp; if (p == *hr) *hr = p->leftp; // if deleting the last element else p->rightp->leftp = p->leftp; free(p); // free memory } ECE 175, Spring 2009
Deleting an Element from the List Calling the deletion function temp = find_name(headl,”Nina”); if(temp == NULL) printf("this name does not exist in the database\n"); else delete_member(temp, &headl, &headr); ECE 175, Spring 2009