C++实现的

(难题)c++ 哔哩哔哩------翻转链表

2019-07-27  本文已影响0人  PreCon

题目描述:对于一个链表 L: L0→L1→…→Ln-1→Ln,
将其翻转成 L0→Ln→L1→Ln-1→L2→Ln-2→…
输入是一串数字,请将其转换成单链表格式之后,再进行操作
输入描述:
一串数字,用逗号分隔
输出描述:
一串数字,用逗号分隔

思路: 翻转链表时需要注意,不能对链表依次访问 L0→Ln→L1→Ln-1→L2→Ln-2→…这样的话,时间会超过题目的需求,所以需要用另一种方法来解决;解决思路一个正向输出链表的前半段,另一是通过栈来输出链表的后半段,两个交替输出就可以了;这样的话,时间就可以很少了,输出后半段的话,利用栈的先入后出原理,具体看代码吧,思路还是很简单的!!!

#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct ListNode
{
    int m_nKey;
    ListNode* m_pNext;
    ListNode(int x) :m_nKey(x), m_pNext(nullptr) {}
};
ListNode* creatList(vector<int>arr)
{
    int len = arr.size();
    ListNode*p = new ListNode(arr[0]);
    ListNode*cur = p;
    for (int i = 1; i < len; i++)
    {
        cur->m_pNext = new ListNode(arr[i]);
        cur = cur->m_pNext;
    }
    return p;
}
int main()
{
    char c = ' ';
    int tmp, flag = 0;
    vector<int>arr;
    while (c!='\n')
    {
        cin >> tmp;
        arr.push_back(tmp);
        c = getchar();
    }
    ListNode *List = creatList(arr);
    ListNode *cur1 = List, *cur2 = List;
    int len = arr.size();
    int right = arr.size();
    stack<ListNode*>nodes;
    while (cur2 != nullptr)
    {
        nodes.push(cur2);
        cur2 = cur2->m_pNext;
    }
    while (right >= len / 2 + 1)
    {
        if (len % 2 != 0)
        {
            if (right == len / 2 + 1)
            {
                cur2 = nodes.top();
                cout << cur2->m_nKey << endl;
            }
            else
            {
                cout << cur1->m_nKey << ",";
                cur1 = cur1->m_pNext;
                cur2 = nodes.top();
                cout << cur2->m_nKey << ",";
                nodes.pop();
            }
            --right;
        }
        else
        {
            if (right == len / 2 + 1)
            {
                cout << cur1->m_nKey << ",";
                cur1 = cur1->m_pNext;
                cur2 = nodes.top();
                cout << cur2->m_nKey<< endl;
            }
            else
            {
                cout << cur1->m_nKey << ",";
                cur1 = cur1->m_pNext;
                cur2 = nodes.top();
                cout << cur2->m_nKey << ",";
                nodes.pop();
            }
            --right;
        }
    }
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读