《剑指offer》面试题5 从头到尾打印链表

原题见于 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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值