当前位置: 代码迷 >> C语言 >> [求助]链表问题
  详细解决方案

[求助]链表问题

热度:140   发布时间:2005-09-27 12:33:00.0
[求助]链表问题

#include <stdio.h> #define NULL 0 #define LEN sizeof(struct student) struct student { int num; struct student *next; }; struct student * input(struct student *head) { struct student *p1,*p2,*p; p1=p2=(struct student*)malloc(LEN); scanf("%d",&p1->num); head=NULL; while(p1->num>0) { if(head==NULL) head=p1; else p2->next=p1; p2=p1; p1=(struct student*)malloc(LEN); scanf("%d",&p1->num); } p2->next=NULL; if(head!=NULL) p=head; do {printf("%d\n",p->num); p=p->next; }while(p!=NULL); return head ; }

seek(struct student *head) /*查找函数*/ { struct student *p; int k; printf("please input the seeking num:\n"); scanf("%d",&k); if(head!=NULL) p=head; do { if(p->num==k) printf("the num is %d\n",*p); else if(p==NULL) printf("don't exist:\n"); p=p->next; }while(p!=NULL); } main() { struct student *head=NULL; head=input(head); seek(head); getch(); } 这个链表在查询时 如果输入的数不存在就会 出错, 请问怎么改才正确呢 ?

[此贴子已经被作者于2005-9-27 17:38:09编辑过]

搜索更多相关的解决方案: 链表  

----------------解决方案--------------------------------------------------------
晕  没人会吗 ?????
----------------解决方案--------------------------------------------------------
怎么了啊?
----------------解决方案--------------------------------------------------------
应该是if、else的设置的不好。
改成下面的试试
if(head!=NULL)
{
  p=head;
  do
   {
     if(p-&gt;num==k)
    {
         printf("the num is %d\n",*p);
         break;
    }
     p=p-&gt;next;
   }while(p!=NULL);
  if(p == NULL)
    printf("don't exits\n");  
}
else
{
   printf("Invalid pointer\n");
  return;
}
----------------解决方案--------------------------------------------------------
  相关解决方案