I'm writing a simple program to figure out how Linked List works, but for now I'm stucking. I don't know which line cause the error or I had a mistake in thinking. I run my program by my hand and it works fine. But when run, it gets error at all choices, didn't work or runtime error. Please help me figure things out!
I think the code explains itself. Thanks everyone who give my thread a look.
BTW, I'm using Pelles C 8 IDE on Windows 10.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct Node {
int data;
struct Node *next;
};
void insl(struct Node *, const int);
void del(struct Node *);
int clear(struct Node *);
void print(struct Node *);
int main(void) {
struct Node *head = NULL;
for ( ; ; ) {
_clrscr();
puts("LINK LIST DEMO");
printf("%s", "Current list: ");
print(head);
puts("\n(0) Free list and exit.");
puts("(1) Insert a node at last.");
puts("(2) Delete last node.");
puts("(3) Free list.");
printf("%s", "Enter your choice: ");
int choice = 0;
scanf("%d", &choice);
switch (choice) {
case 0:
if (clear(head))
puts("\nDone!");
else
puts("\nError!");
scanf("%d", &choice);
return 0;
case 1:
printf("%s", "\nEnter data: ");
int x;
scanf("%d", &x);
insl(head, x);
break;
case 2:
del(head);
break;
case 3:
clear(head);
break;
}
}
}
void insl(struct Node *head, const int x) {
struct Node *new = malloc(sizeof *new);
new->data = x;
new->next = NULL;
if (!head) {
head = new;
return;
}
struct Node *temp = head;
while (!temp->next)
temp = temp->next;
temp->next = new;
}
void del(struct Node *head) {
if (!head)
return;
struct Node *temp = head;
while (!temp->next)
temp = temp->next;
free(temp);
}
int clear(struct Node *head) {
struct Node *temp = head, *save;
if (!temp) {
save = temp->next;
free(temp);
temp = save;
}
head = temp;
if (!head)
return 1;
return 0;
}
void print(struct Node *head) {
if (!head) {
puts("empty");
return;
}
struct Node *temp = head;
while (!temp) {
printf("%d ", temp->data);
temp = temp->next;
}
putchar(10);
}