Build a Linked-List Interactively
#include <stdio.h> #include <stdlib.h> #include <ctype.h> struct Node {// w ww. j a va2s .c o m int value; struct Node *next; }; struct Node *first; struct Node *current; struct Node *newCurrent; int menu(void); void add(void); void show(void); void deleteNode(void); struct Node *create(void); int main() { int choice = '\0'; /* get the while loop to spin */ first = NULL; while (choice != 'Q') { choice = menu(); switch (choice) { case 'S': show(); break; case 'A': add(); break; case 'R': deleteNode(); break; case 'Q': break; default: break; } } return(0); } /* Display the main menu and collect input */ int menu(void) { int ch; printf("S)how, A)dd, R)emove, Q)uit: "); ch = getchar(); while (getchar() != '\n') /* remove excess input */ ; return(toupper(ch)); } /* Add an item to the end of the linked list */ void add(void) { if (first == NULL) { first = create(); current = first; } else { current = first; while (current->next) current = current->next; newCurrent = create(); current->next = newCurrent; current = newCurrent; } printf("Type a value: "); scanf("%d", ¤t->value); current->next = NULL; while (getchar() != '\n') ; } void show(void) { int count = 1; if (first == NULL) { puts("Nothing to show"); return; } puts("Showing all records:"); current = first; while (current) { printf("Record %d: %d\n", count, current->value); current = current->next; count++; } } void deleteNode(void) { struct Node *previous; int r, c; if (first == NULL) { puts("No records to remove"); return; } puts("Choose a record to remove:"); show(); printf("Record: "); scanf("%d", &r); while (getchar() != '\n') ; c = 1; current = first; previous = NULL; while (c != r) { if (current == NULL) { puts("Record not found"); return; } previous = current; current = current->next; c++; } if (previous == NULL) first = current->next; else previous->next = current->next; printf("Record %d removed.\n", r); free(current); } struct Node *create(void) { struct Node *a; a = (struct Node *)malloc(sizeof(struct Node)); if (a == NULL) { puts("Some kind of malloc() error"); exit(1); } return(a); }