【链表】问题 E: 算法2-24 单链表反转

题目描述

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

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

输入

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

输出

针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开

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

样例输入 复制
5 1 2 3 4 5 
0
样例输出 复制
1 2 3 4 5 
5 4 3 2 1 
list is empty
分析:

本题的链表逆转采用类似头插法的策略,首先找到第一个元素和最后一个元素,然后将这个元素插到原本最后一个元素之后,然后找到第二元素,并不断重复这个方法,直到第一个元素和原本最后一个元素重叠。

#include <iostream>

using namespace std;

struct node{
    int data;
    node* next;
};
struct linklist{
    node* head, *rear;
};

void createList(linklist &L){
    L.head = new node;
    L.head -> next = NULL;
    L.rear = L.head;
}
void RearNewNode(linklist &L, int e){
    node* s = new node;
    s -> data = e;
    s -> next = NULL;
    L.rear -> next = s;
    L.rear = s;
}
void FrontNewNode(linklist &L, int e){
    node *s = new node;
    s -> data = e;
    s -> next = L.head -> next;
    if(L.head -> next){
        L.rear = s;
    }
    L.head -> next = s;
}
void PrintList(linklist L){
    node* p = L.head -> next;
    while(p){
        cout << p -> data;
        if(p -> next){
            cout << ' ';
        }else{
            cout << '\n';
        }
        p = p -> next;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    while(cin >> n){
        if(n == 0){
            cout << "list is empty\n";
            continue;
        }
        linklist L;
        createList(L);
        for(int i = 0; i < n; i++){
            int e;
            cin >> e;
            RearNewNode(L, e);
        }

        PrintList(L);

        node* p = L.head -> next;
        node* q = L.rear;
        while(p != q){
            if(q -> next){
                L.rear = p;
            }
            L.head -> next = p ->next;
            p -> next = q -> next;
            q -> next = p;
            p = L.head -> next;
        }

        PrintList(L);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值