-
Notifications
You must be signed in to change notification settings - Fork 4
/
lec13.c
94 lines (82 loc) · 1.4 KB
/
lec13.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
93
94
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
struct Node *head;
struct Node *get_new_node(int x)
{
struct Node *new_node_pointer = (struct Node *)malloc(sizeof(struct Node));
new_node_pointer->data = x;
new_node_pointer->prev = NULL;
new_node_pointer->next = NULL;
return new_node_pointer;
}
void insert_at_head(int x)
{
struct Node *new_node = get_new_node(x);
if (head == NULL)
{
head = new_node;
return;
}
head->prev = new_node;
new_node->next = head;
head = new_node;
}
void insert_at_tail(int x)
{
struct Node *new_node = get_new_node(x);
struct Node *temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
new_node->prev = temp;
}
void print()
{
struct Node *temp = head;
printf("Forward: ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void reverse_print()
{
struct Node *temp = head;
if (temp == NULL)
return;
while (temp->next != NULL)
{
temp = temp->next;
}
printf("Reverse: ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
int main(void)
{
head = NULL;
insert_at_head(2);
print();
reverse_print();
insert_at_head(4);
print();
reverse_print();
insert_at_tail(6);
print();
reverse_print();
return 0;
}