-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProg4.c
114 lines (97 loc) · 2.28 KB
/
Prog4.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* ---------------PROBLEM STATEMENT ---------------
Write a program to count the number of nodes & reverse the single linked list.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int info;
struct Node *next;
} Node;
void display(Node *head)
{
if (head == NULL)
{
printf("List is empty.\n");
return;
}
Node *temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->info);
temp = temp->next;
}
printf("NULL\n");
}
Node *insert_at_end(Node *head, int data)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->info = data;
newNode->next = NULL;
if (head == NULL)
{
// If the list is empty, the new node becomes the head.
head = newNode;
}
else
{
Node *temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
// Attach the new node to the last node.
temp->next = newNode;
}
return head;
}
Node* Rev(Node *head){
if(head == NULL || head->next == NULL){
return head;
}
Node* curr = head;;
Node* prev = NULL;
while(curr != NULL){
Node* save = curr->next;
curr->next = prev;
prev = curr;
curr = save;
}
head = prev;
return head;
}
int main(){
Node *head = (Node *)malloc(sizeof(Node));
head = NULL;
int count = 0;
int data;
char c;
while (1)
{
printf("Insert the data for the linked list : ");
if(scanf("%d", &data) != 1){
printf("\n***** Please Enter a integer value ****** \n");
while (getchar() != '\n'); // Clear the input buffer
continue;
}
head = insert_at_end(head, data);
count++;
printf("Nodes after insertion : ");
display(head);
ask:
printf("Do you want to insert more nodes (y/n) : ");
scanf(" %c",&c);
if(c == 'n'){
break;
}
else if(c != 'y'){
printf("\n***** Please Enter a valid character (y/n) ****** \n");
goto ask;
}
}
printf("\nTotal number of nodes inserted : %d\n",count);
printf("\n**** Reverse of the linked list ******\n");
head = Rev(head);
display(head);
return 0;
}