我的这个c语言链表,现在读入许多数据,怎样逆序输出?最好给代码参考下,谢

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

typedef struct _node{
int value;
struct _node *next;
} Node;

int main() {
Node * head = NULL;
int number;
do{
scanf ("%d",&number );
if (number != -1){
Node *p=(Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
Node * last = head;
if (last){

while (last->next){
last = last->next;
}
last->next = p;
}else head=p;
}
} while (number != -1);

return 0;
}

逆序输出 最简单的方法 是使用递归函数。

void reverse_display(Node * head)
{
    if(head == NULL) return;
    reverse_display(head->next);
    printf("%d,",head->value);
}

这样代码是最简单的。 

追问

不对啊....没有任何输出,直接结束了..

追答

你把你完整代码传上来,我测一下

追问

不用了………我参考了一下一个网友的………能达到目的……没有用递归……但是不是很懂……我把代码发给你………你把思路给我讲讲吧……谢

额……乱码了……等我重弄

私信你了

追答

你这个不能算把链表反序输出,而是链表还是正序输出的,而插入链表数据是“反序”的,也就是所谓的头插法。

新插入的元素 插入在链表的开始部分。

p=(Node*)malloc(sizeof(Node));
p->value = number;//新的节点p
p->next = head -> next; //下面两句 æ˜¯æŠŠp插在head与head->next中间。
head->next=p;

这样 在链表中存的顺序就是与输入的相反了,后来的在前面

温馨提示:答案为网友推荐,仅供参考
相似回答