Skip to content

Instantly share code, notes, and snippets.

@cgradwohl
Created November 15, 2020 01:46
Show Gist options
  • Save cgradwohl/d764ccbfea5d33f18911fde7e91b799d to your computer and use it in GitHub Desktop.
Save cgradwohl/d764ccbfea5d33f18911fde7e91b799d to your computer and use it in GitHub Desktop.
Linked List in C
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
struct Node* prev;
struct Node* next;
} Node;
typedef struct LinkedList {
Node* head;
} LinkedList;
Node* createNode(int key) {
Node* node = (Node *) malloc(sizeof(Node));
node->key = key;
node->prev = NULL;
node->next = NULL;
return node;
}
LinkedList* createList() {
LinkedList* list = (LinkedList *) malloc(sizeof(LinkedList));
list->head = NULL;
return list;
}
int printList(LinkedList *L) {
Node* x = L->head;
while (x != NULL) {
printf("key: %d\n", x->key);
x = x->next;
}
printf("\n\n");
return 0;
}
LinkedList* insertKey(LinkedList *L, int k) {
Node* x = createNode(k);
if (L->head != NULL) {
L->head->prev = x;
}
x->next = L->head;
L->head = x;
return L;
}
Node* searchKey(LinkedList *L, int k) {
Node* x = L->head;
while (x != NULL && x->key != k) {
x = x->next;
}
return x;
}
LinkedList* deleteKey(LinkedList *L, int k) {
Node* x = searchKey(L, k);
if (x == NULL) {
printf("The key, %d, provided does not exist in the list.\n\n", k);
return L;
}
if (x->prev == NULL) {
L->head = x->next;
} else {
x->prev->next = x->next;
}
if (x->next != NULL) {
x->next->prev = x->next;
}
return L;
}
void printNode(Node* node) {
if (!node) {
printf("Node: NULL\n");
} else {
printf("Node: %d\n", node->key);
}
}
int main() {
LinkedList* list = createList();
insertKey(list, 1);
insertKey(list, 2);
insertKey(list, 3);
insertKey(list, 4);
printList(list);
deleteKey(list, 1);
printList(list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment