牛客网-C++剑指offer-第十五题(反转链表)

题目描述

输入一个链表,反转链表后,输出新链表的表头。

 

解题思路:还是比较基础的一道题,主要还是考察链表的操作,主要思路是遍历整个链表的节点,并将每个节点的地址进行存储,然后将其反转,返回表头。

 

参考答案:

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
};


class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {

        if (pHead == NULL || pHead->next == NULL)
            return pHead;

        stack my_stack;

        ListNode* pmove = pHead;
        ListNode* reverselist = NULL;
        ListNode* reverselist_head = NULL;

        while (pmove->next)
        {
            my_stack.push(pmove);
            pmove = pmove->next;
        }

        reverselist = reverselist_head = pmove;

        while (!my_stack.empty())
        {
            reverselist->next = my_stack.top();
            reverselist = reverselist->next;
            my_stack.pop();
        }

        reverselist->next = NULL;

        return reverselist_head;
    }
};


int main()
{
    //创建链表
    vector array_list;

    Solution solution;

    //初始化链表内的参数
    ListNode ListNode7 = {7,NULL};
    ListNode ListNode6 = {6,&ListNode7};
    ListNode ListNode5 = {5,&ListNode6};
    ListNode ListNode4 = {4,&ListNode5};
    ListNode ListNode3 = {3,&ListNode4};
    ListNode ListNode2 = {2,&ListNode3};
    ListNode ListNode1 = {1,&ListNode2};

    //将头指针指向第一个链表的地址
    ListNode *head = &ListNode1;
    ListNode *my_result = NULL;
    ListNode *my_pmove = NULL;

    ListNode *my_head = head;

    my_result = solution.ReverseList(head);

    while (my_result != NULL)
    {
        cout<<"result:"<val<next;
    }

    return 0;
}

 

优化代码(上面算法的时间复杂度超过O(n),以下算法复杂度为O(n)):

//初始化三个指针分别指向第一,二,三个结点
//然后从左往右移动,依次将current指针的next指向前一个节点
//只遍历一遍结点,时间复杂度为O(n)
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        //注意将要赋值的节点是否为空
        if(pHead == NULL || pHead->next == NULL)
            return pHead;

        ListNode* front = pHead;
        ListNode* current = pHead->next;
        ListNode* temp;

        if (current->next == NULL)
        {
            front->next = NULL;
            current->next = front;
            return current;
        } else{
            ListNode* back = current->next;
            front->next = NULL;

            while (back->next != NULL)
            {
                current->next = front;
                front = current;
                current = back;
                back = back->next;
            }
            current->next = front;
            back->next = current;
            return back;
        }
    }
};

 

你可能感兴趣的:(牛客网-C++剑指offer-第十五题(反转链表))