C++反转链表(迭代法,头插法)

迭代法代码:

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

输入输出:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值