-
Notifications
You must be signed in to change notification settings - Fork 0
/
doubly_linked_list.c
81 lines (69 loc) · 1.4 KB
/
doubly_linked_list.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
struct node* prev;
};
void push(struct node** head, int new_data)
{
struct node* new_node
= (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head);
new_node->prev = NULL;
if ((*head) != NULL)
{
(*head)->prev = new_node;
}
(*head) = new_node;
}
void pushBefore(struct node** head, struct node* next_node,
int new_data)
{
if (next_node == NULL)
{
return;
}
struct node* new_node
= (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->prev = next_node->prev;
next_node->prev = new_node;
new_node->next = next_node;
if (new_node->prev != NULL)
{
new_node->prev->next = new_node;
}
else{
(*head) = new_node;
}
}
void printList(struct node* head)
{
struct node* last;
while (head != NULL)
{
printf("%d ", head->data);
last = head;
head = head->next;
}
printf("\n");
while (last != NULL)
{
printf("%d ", last->data);
last = last->prev;
}
}
int main()
{
struct node *head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 5);
pushBefore(&head, head->next, 4);
printList(head);
return 0;
}