codeup|问题 E: 算法2-24 单链表反转

题目描述
根据一个整数序列构造一个单链表,然后将其反转。

例如:原单链表为 2 3 4 5 ,反转之后为5 4 3 2

输入
输入包括多组测试数据,每组测试数据占一行,第一个为大于等于0的整数n,表示该单链表的长度,后面跟着n个整数,表示链表的每一个元素。整数之间用空格隔开
输出
针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开

如果链表为空,则只输出一行,list is empty

样例输入 Copy
5 1 2 3 4 5
0
样例输出 Copy
1 2 3 4 5
5 4 3 2 1
list is empty

#include<bits/stdc++.h>
using namespace std;

struct node
{
    int val;
    struct node *next;
    node(int x): val(x), next(nullptr){}
};

int main()
{
    int n, a;
    while(cin >> n)
    {
        if(n==0)
            cout<< "list is empty" << endl;
        else
        {
            struct node *head = new node(0);
            struct node *p = head;
            while(n--) // 将输入的元素构建成单链表
            {
                cin >> a;
                struct node *last = new node(a);
                p->next = last;
                p = last;
            }

            p = head->next;
            while(p && p->next) // 输出单链表
            {
                cout << p->val << " ";
                p = p->next;
            }
            cout << p->val << endl;

            p = head->next; // 翻转单链表
            struct node *h = new node(0);
            while(p)
            {
                head->next = head->next->next;
                p->next = h->next;
                h->next = p;
                p=head->next;
            }
            delete head;

            struct node *index = h->next; // 输出翻转后的单链表
            while(index && index->next)
            {
                cout << index->val << " " ;
                index = index->next;
            }
            cout << index->val << endl;

        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值