Created
February 20, 2019 20:10
-
-
Save basilwong/f8b2b4e8dfb1fdc027daef66fea3e2c5 to your computer and use it in GitHub Desktop.
Function for deleting a specified element in a basic linked list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Question 1: Delete an item in a linked list */ | |
#include <bits/stdc++.h> | |
typedef struct list_item { | |
int value; | |
list_item* next; | |
} list_item; | |
// Iterates through the items in the linked list and checks for the specified | |
// value. Deletes the value from the list if found. | |
void del_item(list_item *root, int val) | |
{ | |
list_item *temp_item = root; | |
list_item *prev_item = root; | |
int check; | |
do { | |
check = temp_item->value; | |
// Check for specified value. | |
if (check == val) { | |
// Special case for the head. | |
if (temp_item == root) { | |
*root = *temp_item->next; | |
} else{ | |
prev_item->next = temp_item->next; | |
} | |
delete temp_item; | |
return; | |
} | |
prev_item = temp_item; | |
temp_item = temp_item->next; | |
} while (temp_item != NULL); | |
} | |
void print_list(list_item *root) | |
{ | |
list_item *lp=root; | |
while(lp) { | |
printf("%d\n", lp->value); | |
lp=lp->next; | |
} | |
} | |
int main() | |
{ | |
list_item list[6]; | |
list[0].value=1; list[0].next=list+1; | |
list[1].value=2; list[1].next=list+2; | |
list[2].value=3; list[2].next=list+3; | |
list[3].value=4; list[3].next=list+4; | |
list[4].value=5; list[4].next=list+5; | |
list[5].value=6; list[5].next=0; | |
printf("test to delete list item whose value is 3\n"); | |
del_item(list, 6); | |
print_list(list); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment