原题见于 http://ac.jobdu.com/problem.php?pid=1511
输入一个链表,从尾到头打印链表每个节点的值。
分析:
1.使用栈来存储
2.递归打印,每次先打印后面的值
void print(Node *head)
{
if(head->next!=NULL)
{
print(head->next);
}
printf("%d\n",head->data);
}
3.再建立链表的时候,每次插入节点都是从头部插入,这样也能实现。但这样的话似有投机取巧不符题意之嫌。
-
题目描述:
-
输入一个链表,从尾到头打印链表每个节点的值。
-
输入:
-
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
-
输出:
-
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
-
样例输入:
-
1 2 3 4 5 -1
-
样例输出:
-
5 4 3 2 1
解法二代码如下:
// 超时未AC,疑数据量过大导致递归时间开销过大
//
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node *next;
} Node;
Node * create_link(void)
{
Node * head= (Node *)malloc(sizeof(Node));
head->next=NULL;
head->data=0;
Node * link_node;
int x;
while (scanf("%d",&x),x!=-1)
{
Node * new_node= (Node *)malloc(sizeof(Node));
new_node->data=x;
new_node->next=NULL;
link_node=head;
while(link_node->next!=NULL)
{
link_node=link_node->next;
}
link_node->next=new_node;
}
return head;
}
void print(Node *head)
{
if(head->next!=NULL)
{
print(head->next);
}
printf("%d\n",head->data);
}
int main(int argc, const char * argv[])
{
// insert code here...
Node * head;
head=create_link();
print(head->next);
return 0;
}
下面分别是解法二和解法三的提交统计情况:
可见第五组测试数据确实较大,应是递归时间开销太大所致。
解法三代码如下:
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node *next;
} Node;
Node * create_link(void)
{
Node * head= (Node *)malloc(sizeof(Node));
head->next=NULL;
int x;
while (scanf("%d",&x),x!=-1)
{
Node * link_node= (Node *)malloc(sizeof(Node));
link_node->data=x;
if(head->next==NULL)
{
head->next=link_node;
link_node->next=NULL;
}
else
{
link_node->next=head->next;
head->next=link_node;
}
}
return head;
}
int main(int argc, const char * argv[])
{
// insert code here...
Node * head;
head=create_link();
while (head->next!=NULL)
{
head=head->next;
printf("%d\n",head->data);
}
return 0;
}