summaryrefslogtreecommitdiff
path: root/doublylinkedlist.c
diff options
context:
space:
mode:
Diffstat (limited to 'doublylinkedlist.c')
-rw-r--r--doublylinkedlist.c161
1 files changed, 161 insertions, 0 deletions
diff --git a/doublylinkedlist.c b/doublylinkedlist.c
new file mode 100644
index 0000000..e98217a
--- /dev/null
+++ b/doublylinkedlist.c
@@ -0,0 +1,161 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+struct node {
+ int val;
+ struct node *prev;
+ struct node *next;
+};
+
+struct node *head;
+struct node *tail;
+int len = 0;
+
+void
+prepend(int val)
+{
+ struct node *tmp = malloc(sizeof(struct node));
+ tmp->val = val;
+ if (head == NULL) {
+ head = tail = tmp;
+ return;
+ }
+ tmp->val = val;
+ tmp->next = head;
+ head->prev = tmp;
+ head = tmp;
+ ++len;
+}
+
+void
+append(int val)
+{
+ struct node *tmp = malloc(sizeof(struct node));
+ tmp->val = val;
+ if (!tail) {
+ head = tail = tmp;
+ return;
+ }
+ tmp->prev = tail;
+ tail->next = tmp;
+ tail = tmp;
+ ++len;
+}
+
+struct node
+*get_at(int i)
+{
+ struct node *cur = head;
+ for (int j = 0; cur && j < i; ++j) {
+ cur = cur->next;
+ }
+ return cur;
+}
+
+void
+insert_at(int val, int i)
+{
+ if (i > len) {
+ printf("index is greater than the list length\n");
+ } else if (i == len) {
+ append(val);
+ return;
+ } else if (i == 0) {
+ prepend(val);
+ return;
+ }
+ struct node *cur = get_at(i);
+ struct node *tmp = malloc(sizeof(struct node));
+ tmp->next = cur;
+ tmp->prev = cur->prev;
+ cur->prev = tmp;
+
+ if (tmp->prev) {
+ tmp->prev->next = tmp;
+ }
+ ++len;
+}
+
+int
+remove_node(struct node *tmp)
+{
+ --len;
+ if (len == 0) {
+ head = tail = NULL;
+ return -1;
+ }
+
+ if (tmp->prev) {
+ tmp->prev->next = tmp->next;
+ }
+ if (tmp->next) {
+ tmp->next->prev = tmp->prev;
+ }
+
+ if (tmp == head) {
+ head = tmp->next;
+ }
+ if (tmp == tail) {
+ tail = tmp->prev;
+ }
+
+ int val = tmp->val;
+ free(tmp);
+ return val;
+}
+
+int
+remove_val(int val)
+{
+ struct node *cur = head;
+ for (int i = 0; cur && cur->val != val && i < len; ++i) {
+ cur = cur->next;
+ }
+ if (!cur) {
+ return -1;
+ }
+ return remove_node(cur);
+}
+
+int
+remove_at(int i)
+{
+ struct node *tmp = get_at(i);
+ if (!tmp) {
+ return -1;
+ }
+ return remove_node(tmp);
+}
+
+int
+get(int i)
+{
+ get_at(i)->val;
+}
+
+void
+print()
+{
+ struct node *cur = head;
+ while (cur != NULL) {
+ printf("%d ", cur->val);
+ cur = cur->next;
+ }
+ printf("\n");
+}
+
+int
+main()
+{
+ int val, n = 0;
+ printf("How many integers?\n");
+ scanf("%d", &n);
+ for (int i = 0; i < n; ++i) {
+ printf("Enter an integer \n");
+ scanf("%d", &val);
+ prepend(val);
+ print();
+ }
+
+ return 0;
+}