题目1511:从尾到头打印链表


题目描述:

输入一个链表,从尾到头打印链表每个节点的值。

输入:

每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。

输出:

对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。

样例输入:
1
2
3
4
5
-1
样例输出:
5
4
3
2
1

#include <iostream>
using namespace std;

struct LinkNode
{
    int val;
    LinkNode *next;
    LinkNode(int x):val(x),next(NULL){};
};

LinkNode *initList()
{
    LinkNode *root = NULL;
    LinkNode *p, *q;
    int value;
    while(cin>>value&&value!=-1)
    {
        p = new LinkNode(value);
        if(!root)
        {
            root = p;
            q = root;
            continue; //if not, when n =1, it's a loop;
        }
        q->next = p;
        q = q->next;
    }
    return root;
}

LinkNode *reverse(LinkNode *root)
{
    if(!root)
        return NULL;
    LinkNode *p, *q, *temp;
    p = root;
    q = root->next;

    while(q)
    {
        temp = q;
        q = q->next;
        temp->next = p;
        p = temp;
    }
    root->next = NULL;
    return p;
}

void printList(LinkNode *root)
{
    while(root)
    {
        cout<<root->val;
        root = root->next;
            cout<<endl;
    }
}

int main()
{
    LinkNode *root,*newRoot;
    root = initList();
    newRoot = reverse(root);
    printList(newRoot);
    return 0;
}


用cin cout最后一个case超时, 改成printf 和 scanf可过

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值