-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion4.c
63 lines (49 loc) · 1.03 KB
/
question4.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
/*
Iterative program to reverse a linked list
*/
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
void reverse(struct node **head){
//reversing the list
struct node *curr, *prev,*nextNode;
curr = *head;
prev = NULL;
while(curr){
nextNode = curr->link;
curr->link = prev;
prev = curr;
curr = nextNode;
}
*head = prev; //assigning the address the updated value
}
void printList(struct node *t){
if(t){
//interchanging these lines will print it in reverse order
printf("%d\n", t->data);
printList(t->link);
}
}
int main(){
struct node *head = (struct node *)malloc(sizeof(struct node));
struct node *t = head;
int counter = 1;
while(counter<=5){
t->data = counter*10;
if(counter == 5){
t->link = NULL;
}else{
t->link = (struct node *)malloc(sizeof(struct node));
}
t = t->link;
counter++;
}
t = head;
printList(t);
t = head;
reverse(&head); //passing the address of the pointer pointing to the first address of the linked list
printList(head);
}