-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlinked_list.c
66 lines (59 loc) · 1.33 KB
/
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
/*
* Recursive C program to reverse nodes of a linked list and display
* them
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void print_reverse_recursive (struct node *);
void print (struct node *);
void create_new_node (struct node *, int );
//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}
//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}
//Recursive call first
print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}
//Print the linkedlist normal
void print (struct node *head)
{
if (head == NULL)
{
return;
}
printf ("%d ", head -> data);
print (head -> next);
}
//New data added in the start
void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}