-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathreverse-LL.c
77 lines (58 loc) · 1.37 KB
/
reverse-LL.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
#include <stdio.h>
#include <stdlib.h>
struct node{
int val;
struct node *next;
};
void print_list(struct node *head)
{
printf("H->");
while(head)
{
printf("%d->", head->val);
head = head->next;
}
printf("|||\n\n");
}
void insert_front(struct node **head, int value)
{
struct node * new_node = NULL;
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("Failed to insert element. Out of memory");
}
new_node->val = value;
new_node->next = *head;
*head = new_node;
}
void reverse_linked_list(struct node **head) {
struct node *new_head = NULL; /*head of the reversed list*/
struct node *tmp = NULL;
while(*head) {
tmp = *head; /*tmp points the first node of the current list*/
*head = (*head)->next;
/*Insert tmp at the front of the reversed list.*/
tmp->next = new_head;
new_head = tmp;
}
*head = new_head;
}
void main()
{
int count = 0, i, val;
struct node * head = NULL;
printf("Enter number of elements: ");
scanf("%d", &count);
for (i = 0; i < count; i++)
{
printf("Enter %dth element: ", i);
scanf("%d", &val);
insert_front(&head, val);
}
printf("Initial List: ");
print_list(head);
reverse_linked_list(&head);
printf("Reversed List: ");
print_list(head);
}