【15】反转链表

【15】反转链表

  • 时间限制:1秒
  • 空间限制:32768K
  • 本题知识点: 链表
题目描述

输入一个链表,反转链表后,输出链表的所有元素。

牛客网题目链接:点击这里

vs2010代码

#include<iostream>
#include<vector>
using namespace std;
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        vector<int> temp;
        ListNode* P=pHead;
        while(P!=NULL)
        {
            temp.push_back(P->val); //将值顺序存入数组
            P=P->next;
        }
        P=pHead;
        int i=temp.size()-1;
        while(P!=NULL)
        {
            P->val=temp[i];
            i--; P=P->next;
        }
        return pHead;
    }
};

int main()
{
    Solution S1;
    ListNode* H=NULL;
    ListNode* Cur=NULL;
    ListNode* s=NULL;
    //建立头结点
    int t;
    cout<<"输入5个结点"<<endl;
    cout<<"输入第1个结点:";
    cin>>t;
    s=new ListNode(t);
    H=s; Cur=s;
    for(int i=1; i<5; i++)
    {
        cout<<"输入第"<<i+1<<"个结点:";
        cin>>t;
        s=new ListNode(t);
        Cur->next=s;
        Cur=Cur->next;
    }


    //cout<<endl;
    //S1.ReverseList(H);

    //输出结点
    cout<<endl;
    //Cur=H;
    Cur=S1.ReverseList(H);
    while(Cur)
    {
        cout<<Cur->val<<"->";
        Cur=Cur->next;
    }
}

方法二:

三指针反转链表

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(!pHead) return NULL;
        ListNode* Head=pHead;
        ListNode* p1=pHead;
        ListNode* p2=NULL;

        while(p1->next!=NULL){
        p1=p1->next;
        Head->next=p2;
        p2=Head;
        Head=p1;
        }
        Head->next=p2;
        return Head;        
    }
};

代码优化:

ListNode* ReverseList(ListNode* pHead)
{   
    ListNode* pReverseHead=NULL;
    ListNode* pNode=pHead;
    ListNode* pPrev=NULL;
    while(pNode)
    {
        ListNode* pNext=pNode->next;
        if(pNext==NULL)
            pReverseHead=pNode;
        pNode->next=pPrev;

        pPrev=pNode;
        pNode=pNext;
    }
    return pReverseHead;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值