Using linked lists to store, sort, delete, insert, and sort employee information
This problem is very simple, but it involves a wide range of areas, so it has a learning significance.
# Include <stdio. h> # include <string. h> # include <stdlib. h> struct Emplyee {int num; char name [20]; int age; struct Emplyee * next ;}; void main () {struct Emplyee * Create (); void Output (struct Emplyee *); struct Emplyee * Sort (struct Emplyee *); struct Emplyee * Insert (struct Emplyee *, struct Emplyee *); struct Emplyee * Delete (struct Emplyee *, char name [20]); struct Emplyee * s = Create (); Output (s); pr Intf ("the sorting result is \ n"); s = Sort (s); Output (s); struct Emplyee my = {21, "John", 24 }; printf ("the inserted result is \ n"); s = Insert (s, & my); Output (s); printf ("the deleted result is: \ n "); s = Delete (s," John "); Output (s); getchar ();} struct Emplyee * Create () {struct Emplyee * s; struct Emplyee * p = NULL; printf ("enter the names of the three employees: \ n"); for (int I = 0; I <3; I ++) {s = (struct Emplyee *) malloc (sizeof (struct Emplyee); s-> num = I; ge Ts (s-> name); s-> age = 21 + I; if (p = NULL) {s-> next = NULL; p = s ;} else {s-> next = p; p = s;} return p;} void Output (struct Emplyee * sl) {while (sl) {printf ("employee ID: % d \ t name: % s \ t age: % d \ n ", sl-> num, sl-> name, sl-> age ); sl = sl-> next;} struct Emplyee * Sort (struct Emplyee * s) {struct Emplyee temp, * last, * first, * p = s; for (int I = 0; I <3; I ++) {p = s; for (int j = 0; j <I; j ++) {p = p-> nex T;} first = p; struct Emplyee * min = p; while (p! = NULL) {if (p-> age <min-> age) {min = p;} p = p-> next;} temp = * min; min-> age = first-> age; min-> num = first-> num;
Strcpy (min-> name, first-> name); first-> age = temp. age; first-> num = temp. num;
Strcpy (first-> name, temp. name);} return s;} struct Emplyee * Insert (struct Emplyee * s, struct Emplyee * t) {struct Emplyee * p = NULL; struct Emplyee * q = s; while (q-> age <t-> age) & q-> next! = NULL) {p = q; q = q-> next;} if (t-> age <= q-> age) // note that {if (s = q) is not inserted at the end. // The linked list is empty {p = t; p-> next = NULL ;} else {p-> next = t;} t-> next = q;} else // It indicates inserting at the end {q-> next = t; t-> next = NULL;} return s;} struct Emplyee * Delete (struct Emplyee * s, char name [20]) {struct Emplyee * p1 = NULL, * p2 = NULL; p1 = s; while (strcmp (p1-> name, name) & p1-> next! = NULL) {p2 = p1; p1 = p1-> next;} if (! (Strcmp (p1-> name, name) {if (p1 = s) {s = p1-> next ;} else {p2-> next = p1-> next;} // free (p1); this may be a problem with the compiler. If I use it, the compiler will prompt me to touch the breakpoint, in fact, I have not made any breakpoint.} Return s ;}