-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem30.c
More file actions
119 lines (103 loc) Β· 2.57 KB
/
problem30.c
File metadata and controls
119 lines (103 loc) Β· 2.57 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LINE 500
// Node definition for Doubly Linked List
typedef struct Node {
int val;
struct Node* prev;
struct Node* next;
} Node;
// Create a new node with a given value
Node* createNode(int val) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Append a node to the end of the list
void append(Node** headRef, int val) {
Node* newNode = createNode(val);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
Node* temp = *headRef;
while (temp->next != NULL) temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
// Remove all nodes containing the cursed value
Node* removeCursedBeads(Node* head, int target) {
Node* current = head;
while (current) {
if (current->val == target) {
Node* toDelete = current;
if (current->prev) current->prev->next = current->next;
else head = current->next;
if (current->next) current->next->prev = current->prev;
current = current->next;
free(toDelete);
} else {
current = current->next;
}
}
return head;
}
// Print the doubly linked list
void printList(Node* head) {
if (!head) {
printf("(empty list)\n");
return;
}
Node* temp = head;
while (temp) {
printf("%d", temp->val);
if (temp->next) printf(" <-> ");
temp = temp->next;
}
printf("\n");
}
// Free memory of the list
void freeList(Node* head) {
while (head) {
Node* temp = head;
head = head->next;
free(temp);
}
}
// Main function
int main() {
char line[MAX_LINE];
Node* head = NULL;
printf("Enter head: ");
if (!fgets(line, sizeof(line), stdin)) {
printf("!! Invalid input !!\n");
return 1;
}
// Read each value and append to list
char* token = strtok(line, " \n");
while (token != NULL) {
int val;
if (sscanf(token, "%d", &val) == 1) {
append(&head, val);
} else {
printf("!! Invalid input !!\n");
return 1;
}
token = strtok(NULL, " \n");
}
int target;
printf("Enter target: ");
if (scanf("%d", &target) != 1) {
printf("!! Invalid input !!\n");
return 1;
}
head = removeCursedBeads(head, target);
printf("\nModified head: ");
printList(head);
freeList(head);
return 0;
}