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

/*随意输入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;

}

你实际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;
}


head 的值赋值后,就没有变化过,会有什么问题?

链表的定义好像有点问题。。。。