-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem32.c
More file actions
127 lines (105 loc) Β· 2.53 KB
/
problem32.c
File metadata and controls
127 lines (105 loc) Β· 2.53 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 10000
typedef struct Node {
char val[100];
struct Node *next;
} Node;
Node* createNode(const char *val) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}
strcpy(newNode->val, val);
newNode->next = NULL;
return newNode;
}
void append(Node **headRef, const char *val) {
Node *newNode = createNode(val);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
Node *temp = *headRef;
while (temp->next) temp = temp->next;
temp->next = newNode;
}
void printList(Node *head) {
printf("[");
while (head) {
printf("\"%s\"", head->val);
if (head->next) printf(", ");
head = head->next;
}
printf("]\n");
}
void freeList(Node *head) {
while (head) {
Node *temp = head;
head = head->next;
free(temp);
}
}
int getListLength(Node *head) {
int count = 0;
while (head) {
count++;
head = head->next;
}
return count;
}
int isValidIndex(int index, int length){
return(index >= 1 && index <= length);
}
Node* reverseSegment(Node *head, int left, int right) {
if (!head || left == right) return head;
Node dummy;
dummy.next = head;
Node *prev = &dummy;
for (int i = 1; i < left; i++) {
prev = prev->next;
}
Node *current = prev->next;
Node *next = NULL;
for (int i = 0; i < right - left; i++) {
next = current->next;
current->next = next->next;
next->next = prev->next;
prev->next = next;
}
return dummy.next;
}
int main() {
char input[MAX_LEN];
int left, right;
Node *head = NULL;
printf("Enter shopping list items: ");
fgets(input, sizeof(input), stdin);
char *token = strtok(input, " \n");
while (token) {
append(&head, token);
token = strtok(NULL, " \n");
}
int length = getListLength(head);
printf("Enter left index (1-based): ");
scanf("%d", &left);
if (!isValidIndex(left, length)) {
printf("!! Invalid Index !!\n");
freeList(head);
return 1;
}
printf("Enter right index (1-based): ");
scanf("%d", &right);
if (!isValidIndex(right, length)) {
printf("!! Invalid Index !!\n");
freeList(head);
return 1;
}
head = reverseSegment(head, left, right);
printf("Revised List = ");
printList(head);
freeList(head);
return 0;
}