题目来源:http://ac.jobdu.com/problem.php?pid=1511
思路就是C程序设计语言6.6里install函数,将新节点插入表头,这样链表就是后来的节点在前面,打印顺序就是从尾到头了。
具体操作: p-next = q; q = p;
PS:一开始结果是对的,但是运行完就报错,原来是没初始化q,加上q=NULL;后就AC了。
#include
#include
#include
struct list {
struct list *next;
int num;
};
int main()
{
int c;
struct list *p,*q;
q =NULL;
while( scanf("%d",&c)&& c!=-1)
{
p = (struct list *)malloc(sizeof(*p));
if(p == NULL)
return 0;
p->num = c;
p->next = q;
q = p;
}
for(;q != NULL;q = q->next)
printf("%d\n",q->num);
free(p);
p = NULL;
return 0;
}
/**************************************************************
Problem: 1511
User: tsyowen
Language: C
Result: Accepted
Time:100 ms
Memory:3948 kb
****************************************************************/