zoukankan      html  css  js  c++  java
  • HihoCoder1371

    题目链接

    https://vjudge.net/problem/HihoCoder-1371

    迭代法

    #include<bits/stdc++.h>
    using namespace std;
    
    // 迭代法
    
    struct node
    {
        int w;
        node *nex;
        node(int w)
        {
            this->w=w;
            this->nex=NULL;
        }
    };
    
    int main()
    {
        int n;
        while(cin>>n)
        {
            if(n==-1) break;
            // dummy=new node();
            node dummy(0); //其他俩会报错
            // node *dummy = new node(0);
            node *cur=&dummy;
            for(int i=0; i<n; i++)
            {
                int x;
                cin>>x;
                cur->nex=new node(x);
                cur=cur->nex;
            }
            node *head=dummy.nex;
            node *pre=NULL;
            while(head)
            {
                node *nex=head->nex;
                head->nex=pre;
                pre=head,head=nex;
            }
            head=pre;
            while(head->nex)
            {
                cout<<head->w<<" ";
                head=head->nex;
            }
            cout<<head->w<<endl;
        }
        return 0;
    }
    

    递归法

    #include<iostream>
    #include<string.h>
    
    using namespace std;
    #define inf 0x3f3f3f3f
    typedef long long ll;
    
    struct node
    {
        int w;
        node*next;
        node(int w)
        {
            this->w=w;
            this->next=NULL;
        }
    };
    
    
    node*reverseList(node *head)
    {
        if(head==NULL||head->next==NULL) return head;
        node*pre=NULL,*cur=head;  // cur指向链表中的头结点
        while(cur!=NULL)
        {
            node*next=cur->next;// 更换当前结点的箭头方向  pointer 用-> 不用.
            cur->next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
    
    int main()
    {
        int n;
        while(cin>>n,n!=-1)
        {
            node dummy(0),*cur=&dummy;
            for(int i=0;i<n;i++)
            {
                int x;
                cin>>x;
                cur->next=new node(x);
                cur=cur->next;
            }
            node *head=dummy.next,*pre=NULL;
            head=reverseList(head);
            while(head->next)
            {
                cout<<head->w<<" ";
                head=head->next;
            }
            cout<<head->w<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    用js遍历生成数独可行数据(未优化版本)
    JS生成tips小工具
    Iframe使用
    二级指针作输入的三种内存模型
    货品的进出库模型
    约瑟夫问题
    vector
    CUDA并行简单加法
    第一个CUDA程序
    在Ubuntu下安装、配置和测试cuda[复制]
  • 原文地址:https://www.cnblogs.com/OFSHK/p/14532688.html
Copyright © 2011-2022 走看看