3308391854 发表于 2021-10-9 18:18:20

为啥我的单链表查询不行啊,也不报错,只能求助大佬

#include <stdio.h>
#include <stdlib.h>

struct hai
{
    int i;
    struct hai *next;
};

void tm(struct hai **head,int num)// 新结点生成
{
    struct hai *now,*team;
    now = *head;
    now = (struct hai *)malloc(sizeof(struct hai));
    if (now == NULL)
    {
      printf("内存分配失败");
      exit(1);
    }

    now->i = num;

    if(*head != NULL)
    {
      team = *head;
      while (team->next !=NULL)
      {
            team = team->next;
      }
      team->next = now;
      now->next = NULL;
    }

    else
    {
      *head = now;
      now->next = NULL;
    }

}


void nomprint(struct hai *head)// 打印程序块
{
    struct hai *a;
    a = head;
    while (a != NULL)
    {
      printf("%d", a->i);
      a = a->next;
    }

    printf("\n");
}

void releaslibrary(struct hai *head)// 释放
{
    while (head != NULL)
    {
      head = head->next;
      free(head);
    }
}

void cax(struct hai **head,int shu)// 查询链表某个数据
{
    int j = 0,su;
    struct hai *p;
    p = *head;
    su = shu;

    while (p != NULL || j>su)
    {
      p = p->next;
      ++j;
    }

    printf("第%d的数据为%d\n", j, p->i);

}

int main()
{
    struct hai *head = NULL;
    int num,shu;
    while(1)
    {
      printf("请输入数值(-1结束):\n");
      scanf("%d",&num);
      if(num == (-1)) break;

      tm(&head,num);
    }

    while(1)
    {
      printf("请输入要查询的数据(-1结束):\n");
      scanf("%d", &shu);
      cax(&head,shu);
      if (shu == (-1)); break;

    }

    nomprint(head);
    releaslibrary(head);
    return 0;
}

金店长 发表于 2021-10-10 10:26:57

while(p != NULL && (j <= su) ){    /* 需要同时满足,j初始值是0,根本j>u的话根本进不了循环 */

}

3308391854 发表于 2021-10-10 13:07:35

金店长 发表于 2021-10-10 10:26
while(p != NULL && (j u的话根本进不了循环 */

}

感谢大佬,终于解决了
页: [1]
查看完整版本: 为啥我的单链表查询不行啊,也不报错,只能求助大佬