开发者社区> 问答> 正文

链表的一个错误,找了很久也没发现为什么错了。。。

/随意输入n个数字,作为线性链表,遍历该列表返回输入值最小节点的关键字/

#include 
#include 
#include 
#include
struct example 
{
int input;
int keyword;
struct example* next;
};
typedef struct example EXAMPLE;
int main (void)
{
EXAMPLE* head;
EXAMPLE* p;
EXAMPLE* pre;
EXAMPLE* po;
EXAMPLE* pMin;
int n;
int i;
printf("n = ? ");
scanf("%d",&n);

head = (EXAMPLE*)malloc(sizeof(EXAMPLE));
pre = head;

for(i = 1; i <= n; i++)
{
    printf("input = ? ");
    scanf("%d",&pre->input);
    pre->keyword = i;

    p = (EXAMPLE*)malloc(sizeof(EXAMPLE));
    pre->next = p;
    pre = p;
}

pre = NULL;

po = head;
while(po)
{
    printf("%d   %d\n",po->keyword, po->input);
    po = po->next;
}

p = head->next;
pMin = head;   //好像就是这里出了问题,但不知为什么
/* while(p)
{
if(pMin->input > p->input)
pMin = p;
p = p->next;
}*/
printf("min : %d   %d\n",pMin->keyword, pMin->input);



return 0;
}

展开
收起
a123456678 2016-03-20 10:06:31 1895 0
1 条回答
写回答
取消 提交回答
  • 你实际malloc的空间是给p的,pre只是指向这块空间。退出循环后,你只是让pre指向了NULL,与链表中的节点完全没关系啊。
    所以后面你while(po)的时候,很大概率不会因为NULL结束,printf的时候就会段错误了。如果没有那也是意外,因为刚好那块内存是NULL。
    你的逻辑有问题,应该是每次malloc完,判断下返回值,然后就填充该节点,然后加入链表中。
    现在你在一个循环中,是先给之前的节点赋值,再分配新的节点空间,就会导致最后一个分配的节点里面的数据是不确定的(因为你malloc后没有清零操作)仅供参考
    /随意输入n个数字,作为线性链表,遍历该列表返回输入值最小节点的关键字/

    #include
    
    struct example 
    {
    int input;
    int keyword;
    struct example* next;
    };
    
    typedef struct example EXAMPLE;
    
    int main (void)
    {
    EXAMPLE* head;
    EXAMPLE* p;
    EXAMPLE* pre;
    EXAMPLE* po;
    EXAMPLE* pMin;
    int n;
    int i = 1;
    
    printf("n = ? ");
    scanf("%d",&n);
    
    head = (EXAMPLE*)malloc(sizeof(EXAMPLE));
    if(NULL == head)
    {
    printf("no memory\n");
    return 0;
    }
    
    printf("input = ? ");
    scanf("%d",&head->input);
    head->keyword = i;
    head->next = NULL;
    i++;
    
    pre = head;
    for(; i <= n; i++)
    {
    p = (EXAMPLE*)malloc(sizeof(EXAMPLE));
    printf("input = ? ");
    scanf("%d",&p->input);
    p->keyword = i; 
    p->next = NULL;
    
    pre->next = p;  
    pre = p;   
    }
    
    po = head;
    while(po)
    {
    printf("%d %d\n",po->keyword, po->input);
    po = po->next;
    }
    
    p = head->next;
    pMin = head; //好像就是这里出了问题,但不知为什么
    while(p)
    {
    if(pMin->input > p->input)
    pMin = p;
    p = p->next;
    }
    
    printf("min : %d %d\n",pMin->keyword, pMin->input);
    
    return 0;
    }
    2019-07-17 19:08:46
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载