#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Node {
int value;
struct Node* next;
};
struct Node* newNode(int value) {
struct Node *temp = (struct Node*)
malloc(sizeof(struct Node));
temp->value = value;
temp->next = NULL;
return temp;
}
int empty(struct Node* top) {
if (!top) { //top == null
return 1;
}
return 0;
}
void add(struct Node** top, int value) {
struct Node* new = newNode(value);
struct Node* left = NULL;
struct Node* right = *top;
while (right != NULL && right->value < new->value ) {
left = right;
right = right->next;
}
if (left == NULL && right == NULL) {
*top = new;
} else if (left == NULL) {
new->next = *top;
*top = new;
} else {
left->next = new;
new->next = right;
}
}
int exists(struct Node* top, int value) {
if (empty(top)) {
return 0;
}
struct Node* aux = top;
while (aux != NULL && aux->value != value) {
aux = aux->next;
}
if (aux == NULL) {
return 0;
} else {
return 1;
}
}
int delete(struct Node** top, int value) {
if (empty(*top)) {
return 0;
}
struct Node* left = NULL;
struct Node* right = *top;
while (right != NULL && right->value != value) {
left = right;
right = right->next;
}
if (right != NULL) {
if (left == NULL) {
*top = right->next;
} else {
left->next = right->next;
}
free(right);
return 1;
} else {
return 0;
}
}
void addAll(struct Node** source, struct Node** dest) {
}
struct Node* subList(struct Node* source, int from, int to) {
return NULL;
}
int* toArray(struct Node* source) {
return NULL;
}
void printlist(struct Node* top) {
struct Node* aux = top;
printf("list: \n");
while (aux != NULL) {
printf("\tvalue: %d\n", aux->value);
aux = aux->next;
}
}
int main() {
struct Node* top = NULL;
int value;
add(&top, 3);
printlist(top);
add(&top, 1);
printlist(top);
add(&top, 4);
printlist(top);
add(&top, 2);
printlist(top);
value = 2;
if (exists(top, value)) {
printf("value %d exists in list\n", value);
} else {
printf("value %d does not exists\n", value);
}
value = 2;
if (delete(&top, value)) {
printf("value %d not deleted\n", value);
} else {
printf("value %d deleted\n", value);
}
value = 2;
if (exists(top, value)) {
printf("value %d exists in list\n", value);
} else {
printf("value %d does not exists\n", value);
}
printlist(top);
return 0;
}