#include <stdio.h> #define LEN sizeof(struct student)
int n = 0; //全局变量,链表元素的总数
struct student { long num; float score; struct student *next; };
int listmenu(); struct student *input(); long input_delvalue(); struct student *create(); void print(struct student *); struct student *del(struct student *,long); struct student *insert(struct student *,struct student *); int main(int argc, char *argv[]) { struct student *head = NULL; int item; do { item = listmenu(); switch(item) { case -1: break; case 0: item = listmenu(); break; case 1: head = create(); break; case 2: head = insert(head,input()); break; case 3: head = del(head,input_delvalue()); break; case 4: print(head); break; default: break; } }while(-1 != item); system("pause"); return 0; }
struct student *create() { n = 0; struct student *head; struct student *p1,*p2; head = NULL; do { p1 = input(); if (p1->num == 0) { break; } n += 1; if (1 == n) { head = p1; } else { p2->next = p1; } p2 = p1; }while (1); p2->next = NULL; return head; }
void print(struct student *head) { struct student *p; if (0 == n) { printf("not element!\n"); return; } else { printf("\nnow,these %d records are :\n",n); p = head; if (head != NULL) { do { printf("%ld,%5.1f\n",p->num,p->score); p = p->next; }while (p != NULL); } } }
struct student *del(struct student *head,long num) { struct student *p1,*p2; if (head == NULL) { printf("list is NULL!\n"); return head; } p1 = head; while(num != p1->num && p1->next != NULL) { p2 = p1; p1 = p1->next; } if (num == p1->num) { if (p1 == head) { head = p1->next; } else { p2->next = p1->next; } printf("delete :%ld\n",num); n -= 1; } else { printf("%ld not been found!\n",num); } return head; }
struct student *insert(struct student *head,struct student *stu) { struct student *p0,*p1,*p2; p1 = head; p0 = stu; if(NULL == head) { head = p0; p0->next = NULL; } else { while (p0->num > p1->num && p1->next != NULL) { p2 = p1; p1 = p1->next; } if (p0->num <= p1->num) { if (p1 == head) { head = p0; } else { p2->next = p0; } p0->next = p1; } else { p1->next = p0; p0->next = NULL; } } n += 1; return head; }
struct student *input() { struct student *p; p = (struct student *)malloc(LEN); printf("please input data(num,score):\n"); scanf("%ld,%f",&p->num,&p->score); return p; }
long input_delvalue() { printf("pleaes input delete student num:"); long num; scanf("%ld",&num); return num; }
int listmenu() { int item; do { printf("MENU\n\n"); printf("1\tinit link table\n"); printf("2\tadd element\n"); printf("3\tdelete element\n"); printf("4\tlist element\n"); printf("0\treturn system menu\n"); printf("-1\texit\n"); printf("\nyou select:"); scanf("%d",&item); }while(item > 4 || item < -1); return item; }
|