迭代法代码:
#include<iostream>
#include<vector>
using namespace std;
//创建结点结构体
typedef struct ListNode{
int val;
ListNode* next;
}ListNode;
//反转链表,迭代法,三指针
ListNode* ListReverse(ListNode* pNode){
ListNode* pre=nullptr;
ListNode* curr=pNode;
ListNode* next=curr->next;
while(curr){
next=curr->next;
curr->next=pre;
pre=curr;
curr=next;
}
return pre;
}
int main(){
vector<int> a;
while(1){
int x;cin>>x;
a.push_back(x);
if(cin.get()=='\n') break;
}
// 尾插法创建链表
ListNode* pHead=nullptr;
ListNode* pEnd=nullptr;
for(int i=0;i<a.size();i++){
ListNode* pNode=new ListNode{a[i],nullptr};
if(i==0){
pHead=pNode;
pEnd=pHead;
}
else{
pEnd->next=pNode;
pEnd=pEnd->next;
}
}
//反转链表并输出
ListNode* p=pHead;
ListNode* p2=ListReverse(p);
for(int i=0;i<a.size();i++){
cout<<p2->val<<" ";
p2=p2->next;
}
return 0;
}
头插(新建链表)法代码:
#include<iostream>
#include<vector>
using namespace std;
vector<int> a;
//创建结点结构体
typedef struct ListNode{
int val;
ListNode* next;
}ListNode;
//反转链表,头插法新建链表
ListNode* listReverse(ListNode* pNode){
ListNode* pNew=pNode;
ListNode* head=nullptr;
for(int i=0;i<a.size();i++){
ListNode* temp=pNew;
pNew=pNew->next;
if(i==0){
head=temp;
}
else{
temp->next=head;
head=temp;
}
}
return head;
}
int main(){
while(1){
int x;cin>>x;
a.push_back(x);
if(cin.get()=='\n') break;
}
// 尾插法创建链表
ListNode* pEnd=nullptr;
ListNode* pHead=nullptr;
for(int i=0;i<a.size();i++){
ListNode* pNode=new ListNode{a[i],nullptr};
if(i==0){
pEnd=pNode;
pHead=pEnd;
}
else{
pEnd->next=pNode;
pEnd=pEnd->next;
}
}
//反转链表并输出
ListNode* p=pHead;
ListNode* p2=listReverse(p);
for(int i=0;i<a.size();i++){
cout<<p2->val<<" ";
p2=p2->next;
}
return 0;
}
输入输出: