summaryrefslogtreecommitdiff
path: root/d_linkedlist.c
diff options
context:
space:
mode:
authoroskar <[email protected]>2024-05-10 23:41:25 +0200
committeroskar <[email protected]>2024-05-10 23:41:25 +0200
commitec3079e3f4a0124c744ec7e5b7a3fe78d2bbca77 (patch)
tree3cee44f4f691751528d0e254370596f73ab87ca7 /d_linkedlist.c
parent3b2246ab2a255710a3ef02fb0f9f19dc92e528a7 (diff)
Implemented doubly linked list, fixed issued with singly linked list. Added some nicer visualization for both of them.
Diffstat (limited to 'd_linkedlist.c')
-rw-r--r--d_linkedlist.c76
1 files changed, 76 insertions, 0 deletions
diff --git a/d_linkedlist.c b/d_linkedlist.c
new file mode 100644
index 0000000..025bbb9
--- /dev/null
+++ b/d_linkedlist.c
@@ -0,0 +1,76 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+
+// Singly linked list demo
+
+struct waster {
+ int gg;
+ struct waster *prev;
+ struct waster *next;
+};
+
+struct waster *newnode () {
+
+ struct waster *new = malloc(sizeof(struct waster));
+ return new;
+}
+
+struct waster *llist (uint64_t count) {
+
+ struct waster *wr1 = malloc(sizeof(struct waster));
+ struct waster *head = wr1;
+ wr1->gg = 0; // Data for first node
+ wr1->prev = NULL; // There is no previous node
+ wr1->next = newnode(); // Make new node, next points to it
+ struct waster *prv = wr1; // Make prv point to current node
+ wr1 = wr1->next; // Make wr1 point to next node
+
+
+ for (uint64_t i = 1 ; i < count ; i++) { // Actual loop starts
+
+ wr1->gg = i; // Data for 2nd node
+ wr1->prev = prv; // make prev point to prv = wr1 = last node
+ if (i == count-1) {
+ wr1->next = NULL;
+ } else {
+ wr1->next = newnode(); // Make next node, next points to it
+ }
+ prv = wr1; // prv points to current node
+ wr1 = wr1->next; // Make wr1 point to the next node
+
+ }
+
+ wr1 = NULL;
+ return head;
+}
+
+void freellist(struct waster *wr1) {
+ //printf("freelist \n");
+ struct waster *save;
+ while (wr1 != NULL) {
+ save = wr1;
+ wr1 = wr1->next;
+ free(save);
+ }
+}
+
+int main () {
+
+ struct waster *wr1 = llist(20);
+ struct waster *p;
+ for (p = wr1 ; p != NULL ; p = p->next) {
+ void *prev = (void*)p->prev;
+ void *next = (void*)p->next;
+ printf("\n------%p----------",(void *)p);
+ printf("\ndata: %d\nprev: %p\nnext: %p\n", p->gg, prev, next);
+ printf("-----------------------------\n");
+ }
+
+ freellist(wr1);
+ return 0;
+}