-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoublyLinkedList.c
More file actions
112 lines (99 loc) · 2.27 KB
/
doublyLinkedList.c
File metadata and controls
112 lines (99 loc) · 2.27 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
typedef struct {
Node *head, *tail;
int size;
} List;
int append(List *lista, int value) {
Node *new = (Node*) malloc(sizeof(struct node));
new-> data = value;
if (lista-> head == NULL) {
lista-> head = new;
lista-> tail = new;
new-> next = NULL;
} else {
lista-> tail-> next = new;
new-> prev = lista-> tail;
lista-> tail = new;
lista-> tail-> next = NULL;
}
lista-> size++;
return 0;
}
bool insert(List *lista, int value, int position) {
Node *new = (Node*) malloc(sizeof(Node));
Node *current = lista-> head;
Node *previous = current-> prev;
new-> data = value;
if (position > lista-> size) {
printf("A posicao indicada e maior que o tamanho da lista.\n");
return false;
}
for (int index = 0; index != position; index++) {
previous = current;
current = current-> next;
}
previous-> next = new;
new-> prev = previous;
new-> next = current;
current-> prev = new;
printf("Item %i adicionado a lista.\n", value);
lista-> size++;
return true;
}
void delete(List *lista, int value) {
Node *current = lista-> head;
Node *previous = current-> prev;
while (current != NULL && current-> data != value) {
previous = current;
current = current-> next;
if (current-> data == value) {
previous-> next = current-> next;
current-> next-> prev = previous;
}
}
lista-> size--;
free(current);
}
bool search(List *lista, int value) {
Node *current = lista-> head;
int index = 0;
printf("\nO valor %i aparece nas seguintes posicoes: ", value);
printf("[ ");
while (current) {
if (current-> data == value)
printf("%i, ", index);
index++;
current = current-> next;
}
printf("]\n\n");
}
void displayList(List *lista) {
Node *current = lista-> head;
printf("Tamanho da lista: %i\n", lista-> size);
printf("[ ");
for (current; current != NULL; current = current-> next) {
printf("%d-> ", current-> data);
}
puts("NULL ]\n");
}
int main() {
List lista;
lista.head = NULL;
lista.tail = NULL;
lista.size = 0;
append(&lista, 1);
append(&lista, 2);
append(&lista, 2);
append(&lista, 3);
search(&lista, 2);
// delete(&lista, 2);
insert(&lista, 7, 1);
displayList(&lista);
}