|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <stdio.h>
- #include <stdlib.h>
- struct Student
- {
- long num;
- float socer;
- struct Student *next;
- };
- struct Student * creat();
- void print(struct Student *head);
- struct Student * del_linklist(long num , struct Student *head);
- int main(void)
- {
- struct Student *head;
- long num;
- head = creat();
- puts("");
- print(head);
- puts("");
- printf("请输入要删除的学号:");
- scanf("%ld",num);
- head = del_linklist(num , head);
- puts("");
- print(head);
- return 0;
- }
- struct Student * creat()
- {
- struct Student *head , *p1 , *p2;
- head = NULL;
- int n = 0;
- p1 = p2 = (struct Student *)malloc(sizeof(struct Student));
- printf("请输入学号:");
- scanf("%ld",&p1->num);
- printf("请输入分数:");
- scanf("%f",&p1->socer);
- while(p1->socer)
- {
- n++;
- if(n == 1)
- {
- head = p1;
- }
- else
- {
- p2->next = p1;
- }
-
- p2 = p1;
- p1 = (struct Student *)malloc(sizeof(struct Student));
-
- printf("请输入学号:");
- scanf("%ld",&p1->num);
-
- printf("请输入分数:");
- scanf("%f",&p1->socer);
-
- }
- p2->next = NULL;
- return head;
- }
- void print(struct Student *head)
- {
- while(head)
- {
- printf("学号:%ld 分数:%.2f\n",head->num , head->socer);
- head = head->next;
- }
- }
- struct Student * del_linklist(long num , struct Student *head)
- {
- struct Student *p1 , *p2;
- p1 = head;
- while(p1)
- {
- if (p1->num != num)
- {
- p2 = p1;
- p1 = p1->next;
- }
- else
- {
- p2->next = p1->next;
- }
- }
- return head;
- }
复制代码
为什么无法完成链表的删除,是哪里除了问题?
本帖最后由 sunrise085 于 2020-4-13 14:15 编辑
因为你的删除函数中,找到对应节点并删除后,没有退出循环,然后就在那个节点处死循环了。
另外,你没有处理删除头结点的情况。若删除的是头结点,那么还是会出错。
- struct Student * del_linklist(long num , struct Student *head)
- {
- struct Student *p1 , *p2;
- p1 = head;
- while(p1)
- {
- if (p1->num != num)
- {
- p2 = p1;
- p1 = p1->next;
- }
- else //若是找到了对应的节点,那程序就会进入else语句块,然后p1不在改变,while循环条件也不在改变,进入死循环。应该在else中处理完要删除的节点后用break跳出循环
- {
- if (p1==head)
- head=p1->next;
- else
- p2->next = p1->next;
- break;
- }
- }
- return head;
- }
复制代码
|
|