summaryrefslogtreecommitdiff
path: root/src/01/05/doubly_linked_list.c
blob: 006b1941e38d5134e563d18c343331eea9cb8149 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "doubly_linked_list.h"
#include <stdio.h>
#include <stdlib.h>

Node *initialize(int data) {
  Node *node = malloc(sizeof(Node));
  node->data = data;
  node->next = NULL;
  node->prev = NULL;
  return node;
}

Node *add(Node *head, int data) {
  Node *tail;
  Node *tmp = head;

  while (tmp) {
    if (!tmp->next)
      break;
    tmp = tmp->next;
  }
  tail = tmp;
  tail->next = initialize(data);
  tail->next->prev = tail;
  return tail->next;
}

Node *get(Node *from, int index) {
  if (!from || index < 0)
    return NULL;

  while (index > 0 && from) {
    from = from->next;
    index--;
  }
  return from;
}

static int size(Node *head) {
  int i = 0;
  for (Node *tmp = head; tmp && tmp != NULL; tmp = tmp->next)
    i++;
  return i;
}

static void assign_next(Node *self, Node *other) {
  if (self)
    self->next = other;

  if (other)
    other->prev = self;
}

static void assign_prev(Node *self, Node *other) {
  if (self)
    self->prev = other;

  if (other)
    other->next = self;
}

Node *reverse(Node *head) {
  Node *tmp = NULL;
  Node *current = head;

  while (current != NULL) {
    tmp = current->prev;
    current->prev = current->next;
    current->next = tmp;
    current = current->prev;
  }
  return tmp ? tmp->prev : head;
}

static void print(Node *node) {
  if (node->prev && node->next)
    printf("(%d<%d>%d)", node->prev->data, node->data, node->next->data);
  else if (node->next)
    printf("(nil<%d>%d)", node->data, node->next->data);
  else
    printf("(%d<%d>nil)", node->prev->data, node->data);
}

void inspect(Node *node) {
  if (!node)
    return;

  printf("[ ");
  while (node) {
    print(node);
    printf(" ");
    node = node->next;
  }
  printf("]\n");
}