forked from amritanand-py/cps02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathO 02 - Printing the Linked List in Reverse.c
76 lines (63 loc) · 1.53 KB
/
O 02 - Printing the Linked List in Reverse.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
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
typedef struct LinkedListNode LinkedListNode;
struct LinkedListNode {
int val;
LinkedListNode *next;
};
LinkedListNode* _insert_node_into_singlylinkedlist(LinkedListNode *head, LinkedListNode *tail, int val) {
if(head == NULL) {
head = (LinkedListNode *) (malloc(sizeof(LinkedListNode)));
head->val = val;
head->next = NULL;
tail = head;
}
else {
LinkedListNode *node = (LinkedListNode *) (malloc(sizeof(LinkedListNode)));
node->val = val;
node->next = NULL;
tail->next = node;
tail = tail->next;
}
return tail;
}
//BODY STARTS HERE
/*
* Complete the function below.
*/
/*
For your reference:
LinkedListNode {
int val;
LinkedListNode *next;
};
*/
void ReversePrint(LinkedListNode* head) {
if(head){
ReversePrint(head->next);
printf("%d ",head->val);
}
}
//BODY ENDS HERE
int main()
{
int head_size = 0;
LinkedListNode* head = NULL;
LinkedListNode* head_tail = NULL;
scanf("%d\n", &head_size);
for(int i = 0; i < head_size; i++) {
int head_item;
scanf("%d", &head_item);
head_tail = _insert_node_into_singlylinkedlist(head, head_tail, head_item);
if(i == 0) {
head = head_tail;
}
}
ReversePrint(head);
return 0;
}