Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cstdlib>
- #define _CRT_SECURE_NO_WARNINGS
- struct Node
- {
- Node * next;
- Node * prev;
- int key;
- };
- struct List
- {
- Node * first;
- Node * last;
- };
- void swap(Node * a)
- {
- Node * b = a->next;
- a->next = a->prev;
- a->prev = b;
- }
- int push(List * l, int a)
- {
- Node * q = (Node *)malloc(sizeof(Node));
- if (!q)
- return 0;
- q->key = a;
- l->last->prev->next = q;
- q->prev = l->last->prev;
- q->next = l->last;
- l->last->prev = q;
- return 1;
- }
- int unshift(List* l, int a)
- {
- Node * q = (Node *)malloc(sizeof(Node));
- if (!q)
- return 0;
- q->key = a;
- l->first->next->prev = q;
- q->next = l->first->next;
- q->prev = l->first;
- l->first->next = q;
- return 1;
- }
- int shift(List* l, int* q)
- {
- Node* a = l->first->next;
- *q = l->first->next->key;
- l->first->next->next->prev = l->first;
- l->first->next = l->first->next->next;
- free(a);
- return 1;
- }
- int pop(List* l, int* q)
- {
- Node* a = l->last->prev;
- *q = l->last->prev->key;
- l->last->prev->prev->next = l->last;
- l->last->prev = l->last->prev->prev;
- free(a);
- return 1;
- }
- int reverse(List* l)
- {
- Node* a = l->first;
- Node* b;
- while (a != NULL)
- {
- swap(a);
- a = a->prev;
- }
- b = l->first;
- l->first = l->last;
- l->last = b;
- return 1;
- }
- List* list_new()
- {
- List* a = (List*)malloc(sizeof(List));
- Node* q = (Node*)malloc(sizeof(Node));
- Node* w = (Node*)malloc(sizeof(Node));
- q->key = 0;
- w->key = 0;
- q->prev = NULL;
- w->next = NULL;
- q->next = w;
- w->prev = q;
- a->first = q;
- a->last = w;
- return a;
- }
- void list_delete(List* l)
- {
- Node* a = l->first;
- Node* b;
- while (a != NULL)
- {
- b = a->next;
- free(a);
- a = b;
- }
- free(l);
- }
- int main()
- {
- List* l = list_new();
- int q = 3, w = 5;
- push(l, q);
- for (Node* i = l->first; i; i = i->next)
- printf("%i ", i->key);
- printf("\n");
- unshift(l, w);
- for (Node* i = l->first; i; i = i->next)
- printf("%i ", i->key);
- printf("\n");
- reverse(l);
- for (Node* i = l->first; i; i = i->next)
- printf("%i ", i->key);
- printf("\n");
- pop(l, &q);
- for (Node* i = l->first; i; i = i->next)
- printf("%i ", i->key);
- printf("\n");
- shift(l, &w);
- for (Node* i = l->first; i; i = i->next)
- printf("%i ", i->key);
- printf("\n");
- list_delete(l);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment