zoukankan      html  css  js  c++  java
  • 反转链表

    题目描述

    输入一个链表,反转链表后,输出链表的所有元素。
    #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;
        }
    }
  • 相关阅读:
    spring3.2以后的cglib的jar包问题
    maven入门程序(二)
    maven安装配置(myeclipse)(一)
    spring中得到servletContext对象方法
    ftp上传java代码
    FileZilla ftp服务器安装
    spring junit参数
    说一说Servlet的生命周期?
    Servlet API中forward()与redirect()的区别?
    request.getAttribute()和 request.getParameter()有何区别?
  • 原文地址:https://www.cnblogs.com/dshn/p/8809218.html
Copyright © 2011-2022 走看看