-
-
Save pavlos-io/59e8230f494f47e5338fcb72ea1ad0d0 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
typedef struct list List; | |
typedef struct node Node; | |
struct node { | |
int data; | |
Node* next; | |
}; | |
struct list { | |
Node* head; | |
}; | |
List* initList(){ | |
List* ll = (List*)malloc(sizeof(List)); | |
if(!ll) return NULL; | |
ll->head = NULL; | |
return ll; | |
} | |
void destroyList(List* ll){ | |
Node* curr = ll->head; | |
while(curr != NULL){ | |
Node* tmp = curr->next; | |
free(curr); | |
curr = curr->next; | |
} | |
free(ll); | |
} | |
bool addNode(int data, List* ll){ | |
Node* newNode = (Node*)malloc(sizeof(Node)); | |
if(!newNode) return false; | |
newNode->data = data; | |
newNode->next = NULL; | |
if(!ll->head){ | |
ll->head = newNode; | |
} | |
else{ | |
newNode->next = ll->head; | |
ll->head = newNode; | |
} | |
return true; | |
} | |
bool deleteNode(int data, List* ll){ | |
Node* prev = NULL; | |
Node* curr = ll->head; | |
bool found = false; | |
while(curr && curr->data != data){ | |
prev = curr; | |
curr = curr->next; | |
} | |
if(curr){ | |
if(curr->data == data) | |
found = true; | |
} | |
else | |
return found; | |
if(prev){ | |
prev->next = curr->next; | |
} | |
else{ | |
ll->head = curr->next; | |
} | |
free(curr); | |
return found; | |
} | |
void traverseList(List* ll){ | |
printf("%s\n", "Traversing: "); | |
Node* curr = ll->head; | |
while(curr != NULL){ | |
printf("%d\n", curr->data); | |
curr = curr->next; | |
} | |
} | |
int main(){ | |
List* ll = initList(); | |
addNode(55, ll); | |
addNode(65, ll); | |
traverseList(ll); | |
deleteNode(65, ll); | |
traverseList(ll); | |
destroyList(ll); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment