-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
92 lines (77 loc) · 2.05 KB
/
main.c
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
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
struct Node {
int data;
struct Node* previous;
};
struct List {
struct Node* lastNode;
int(*length)(struct List*);
void(*printListByLastNode)(struct Node*);
void(*enqueue)(int, struct List*);
void(*dequeue)(struct List*);
};
void printNode(struct Node *node){
printf("DATA: %d | THIS ADDRESS: %x | PREVIOUS ADDRESS: %x\n", node->data, node, node->previous);
}
int length(struct List* list){
int counter = 0;
struct Node *n = list->lastNode;
while(n){
n = n->previous;
counter++;
}
return counter;
}
void printListByLastNode(struct Node* n)
{
while (n) {
printNode(n);
n = n->previous;
}
}
struct Node * newNode (int data, struct Node *previous) {
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
(*node).data = data;
if(previous){ (*node).previous = previous; }
else node->previous = NULL;
return node;
}
void dequeue(struct List *list) {
struct Node* node = list->lastNode;
while(node){
if(node->previous->previous == NULL) break;
node = node->previous;
}
node->previous = NULL;
}
void enqueue(int data, struct List *list){
struct Node *node = NULL;
if (list->lastNode != NULL) node = newNode(data, list->lastNode);
else node = newNode(data, NULL);
list->lastNode = node;
}
struct List* newList(){
struct List *list = (struct List *) malloc(sizeof (struct List));
list->lastNode = NULL;
list->length = &length;
list->printListByLastNode = &printListByLastNode;
list->enqueue = &enqueue;
list->dequeue = &dequeue;
return list;
}
int main()
{
struct List* list = newList();
list->enqueue(11, list);
list->enqueue(22, list);
list->enqueue(33, list);
list->enqueue(44, list);
list->printListByLastNode(list->lastNode);
list->dequeue(list);
printf("AFTER DEQUEUE ************\n");
list->printListByLastNode(list->lastNode);
printf("\nList Size: %d", list->length(list));
return 0;
}