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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2020-03-14 寒假Day50:51nod-3047-位移运算
2020-03-14 寒假Day50:CodeForces1324C-Frog Jumps-思维