C语言题目4
//用C语言编写程序:建立一个顺序排列环状链表,有一个header指针指向最小节点(整数5)。 //输入一个整数,如果该整数在链表中存在,则删除该节点,并且header指针仍然指向最小的节点; //若不存在,则不作任何操作,最后输出链表中的所有数据。 #include "stdio.h" #include "stdlib.h" typedef struct node{ int x; struct node *next; }llnode; void showList(llnode* head) { llnode* p=head; int i = 0; printf("一共有%d个元素,链表中的数据如下:",head->x); p = head->next; while(i < 3*(head->x)) { printf("%d ",p->x); p = p->next; i = i+1; if(i%(head->x)==0) { printf("---loop--- "); } } printf("...\n"); } int main() { int number=0; llnode* head = (llnode *)malloc(sizeof(llnode)); llnode* p=head; llnode* q=head; llnode* start=head; char buffer; int find=0; head->x = 0;//用来存储数据节点个数 head->next = NULL; printf("请输入初始化链表的整数,数字之间用空格隔开,以输入#并回车结束:"); while(scanf("%d",&number)) { llnode *n = (llnode *)malloc(sizeof(llnode)); n->x = number; n->next = NULL; //如果没有数据节点 if(head->next == NULL) { head->next = n; head->x ++; n->next = n; } //如果用修改head指向 else if((n->x) < (head->next->x)) { p = head->next; if(p->next == p)//只有一个数据节点 { p->next = n; head->next = n; n->next = p; } else { p = p->next; while(p->next != head->next) { p = p->next; } n->next = head->next; p->next = n; head->next = n; } head->x ++; } //如果不用修改head指向 else { find = 0; p = head->next->next; q = head->next; start = q; while(1) { if((n->x)>(p->x)) { p = p->next; q = q->next; } else { q->next = n; n->next = p; head->x ++; break; } if(q->next == start) { n->next = p; q->next = n; head->x ++; break; } } } } showList(head); while((buffer = getchar())!='\n' && buffer!=EOF);//具备可移植性的清空缓冲区方法 printf("顺序循环链表已经建立,请输入要删除的整数,输入#并回车退出程序:"); while(scanf("%d", &number)) { p = head->next; //用修改head指向 if(p->x == number) { if(p->next == p) { free(p); head->next = NULL; } else { p = p->next; while(p->next != head->next) { p = p->next; } q = head->next; p->next = q->next; head->next = q->next; free(q); } head->x --; } //后续数据节点 else { q = p; start = q; p = p->next; while(1) { if(p->x != number) { p = p->next; q = q->next; } else { q->next = p->next; free(p); head->x --; break; } if(p == start) { break; } } } showList(head); while((buffer = getchar())!='\n' && buffer!=EOF);//具备可移植性的清空缓冲区方法 printf("顺序循环链表已经建立,请输入要删除的整数,输入#并回车退出程序:"); } return 1; }