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;
}