-
Notifications
You must be signed in to change notification settings - Fork 26
/
DoublyLL.c
63 lines (55 loc) · 1.55 KB
/
DoublyLL.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
// Implementing Doubly linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
struct Node *prev;
};
struct Node *head;
struct Node *CreateNode() {
struct Node *new = (struct Node*) malloc(sizeof(struct Node));
return new;
}
void Insert(int val) { /*Inserting element at head*/
struct Node *NewNode = CreateNode(); /*NewNode is created everytime function is called*/
NewNode->value = val; /*Value assigned to NewNode*/
NewNode->next = head; /*NewNode's next points to head*/
NewNode->prev = NULL; /*NewNode's previous points to NULL*/
if (head != NULL) {
head->prev = NewNode;
}
head = NewNode;
}
void Display() {
struct Node *temp = head;
printf("\nForward:\n"); /*Printing normally in forward manner*/
while(temp!=NULL) {
printf("%d ",temp->value);
temp = temp->next;
}
}
void ReverseDisplay() {
struct Node *temp = head;
while(temp->next!=NULL) { /*Moving to the last node*/
temp = temp->next;
}
printf("\nBackward:\n"); /*Printing in backward manner*/
while(temp!=NULL) {
printf("%d ",temp->value);
temp = temp->prev;
}
printf("\n");
}
void main() {
int n, val;
printf("Enter number of elements: ");
scanf("%d",&n);
for (int i=0; i<n; i++) {
printf("Enter element: ");
scanf("%d",&val);
Insert(val); /*Inserting value everytime loop executes*/
}
Display();
ReverseDisplay();
}