反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;


struct ListNode
{
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL){}
};
class Solution
{
public:
    ListNode* ReverseList(ListNode* pHead)
    {
        if(!pHead||pHead->next==NULL) return pHead;

        ListNode *p=NULL;//p指向逆方向(链向左)
        ListNode *q=NULL;//q指向正方向(链向右)

        while(pHead!=NULL)
        {
            q=pHead->next;  //首先记录当前节点的下一个节点,(保存起来,好在最后一句 pHead=q;继续把下一个节点反转)
            pHead->next=p;  //让当前节点指向前一个节点,就形成了这个节点的反转,此时pHead的指针方向是向左的
            p=pHead;  //p指向的就是反向的指针
            pHead=q;  //pHead的指针方向重新指向右
        }

        return p;
    }
};

int main()
{
    Solution s;
    int n;
    struct ListNode *head=NULL,*p=NULL,*key=NULL,*x;
    scanf("%d",&n);
    head=(struct ListNode*)malloc(sizeof(struct ListNode));
    p=(struct ListNode*)malloc(sizeof(struct ListNode));
    head->next=p;
    for(int i=0; i<n; ++i)
    {
        scanf("%d",&p->val);
        p->next=(struct ListNode*)malloc(sizeof(struct ListNode));
        x=p;
        p=p->next;
    }
    x->next=NULL;
    p=head->next;
/*
    for(int i=0; i<n; i++)
    {
        printf("%d",p->val);
        p=p->next;
    }
    p=head->next;
    */
    key=s.ReverseList(p);
    while(key!=NULL)
    {
        printf("%d",key->val);
        key=key->next;
    }
}

 

posted @ 2018-04-12 17:37  Lincy*_*  阅读(189)  评论(0编辑  收藏  举报