Skip to content

Instantly share code, notes, and snippets.

@maciejczyzewski
Last active December 11, 2017 10:21
Show Gist options
  • Save maciejczyzewski/dc2e5b1338d45205e3fa03bb986e8e7c to your computer and use it in GitHub Desktop.
Save maciejczyzewski/dc2e5b1338d45205e3fa03bb986e8e7c to your computer and use it in GitHub Desktop.
Doubly linked list in C. (dynamic/pointer-based tree) https://en.wikipedia.org/wiki/Doubly_linked_list
#include <stdio.h>
#include <stdlib.h>
#define pf printf
#define oo 0x7FFFFFFF
#define nodeptr struct node_t*
struct node_t {
int val;
nodeptr rr;
nodeptr ll;
};
nodeptr new_node(int val) {
nodeptr x
= (nodeptr)malloc(sizeof(struct node_t));
x->val = val; x->ll = NULL; x->rr = NULL;
return x;
}
nodeptr list_ll;
nodeptr list_rr;
void new_list(void) {
list_ll = new_node(-oo);
list_rr = new_node(+oo);
list_ll->rr = list_rr;
list_rr->ll = list_ll;
}
////////////////////////////////////////////////////////////////////////////////
#define PUSH(x, y, _val, _inf) \
list_##x->val = _val; \
list_##x->x = new_node(_inf); \
list_##x->x->y = list_##x; \
list_##x = list_##x->x; \
#define POP(x, y, _inf) \
list_##x = list_##x->y; \
list_##x->x = NULL; \
list_##x->val = _inf; \
void push_left(int x)
{ PUSH(ll, rr, x, -oo); }
void pop_left(void)
{ POP(ll, rr, -oo); }
void push_right(int x)
{ PUSH(rr, ll, x, +oo); }
void pop_right(void)
{ POP(rr, ll, +oo); }
////////////////////////////////////////////////////////////////////////////////
#define DEBUG(x, y, _inf) \
nodeptr t = list_##x; \
while (t->val != _inf) { \
if (t->val == +oo || \
t->val == -oo) goto next; \
pf("[%d]", t->val); \
next: t = t-> y; } \
void debug_left(void)
{ DEBUG(ll, rr, +oo); }
void debug_right(void)
{ DEBUG(rr, ll, -oo); }
////////////////////////////////////////////////////////////////////////////////
int main() {
new_list();
// (1)
push_left(5);
push_left(2);
push_left(1200);
push_right(10);
push_right(20);
push_right(11);
push_right(12);
push_right(200);
push_right(15);
// (2)
pop_right();
pop_left();
pop_left();
push_right(25);
push_right(100);
// (1) [1200][2][5][10][20][11][12][200][15]
// (2) X X X + [25][100]
pf("=== @1: CASE ===\n");
debug_left(); pf("\n");
pf("=== @2: CASE ===\n");
debug_right(); pf("\n");
return 0;
}
=== @1: CASE ===
[5][10][20][11][12][200][25][100]
=== @2: CASE ===
[100][25][200][12][11][20][10][5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment