C++ 反转链表

参考链接:链表翻转的图文讲解(递归与迭代两种实现)

这里主要写了非递归的实现

反转的函数实现:

LNode *reverList(LNode *&head){
	if(head == nullptr || head->next == nullptr)
		return head;
	
	LNode *pre = nullptr,*cur = head;//注意pre的初始值是nullptr,cur是head 
	while(cur != nullptr){
		LNode *last = cur->next;
		cur->next = pre;
		pre = cur;
		cur = last;
	}
	
	head = pre;
	return head;
}

全部代码如下:

#include<stdio.h>
#include<malloc.h> 

typedef struct LNode{
	int data;
	struct LNode *next;
}LNode;

LNode *createList(LNode *&head,int arr[],int n);
LNode *reverList(LNode *&head);
void show(LNode *head);

int main(){
	LNode *head = nullptr;
	int arr[10] = {42,65,23,67,134,98,432,87,879,634};
	createList(head,arr,sizeof(arr)/sizeof(arr[0]));
	show(head);
	
	reverList(head);
	show(head);
	
	return 0;
} 

//构造不带头结点的链表 
LNode *createList(LNode *&head,int arr[],int n){
	if(n == 0)
		return nullptr; 
	head = new LNode();
	head->data = arr[0];
	head->next = nullptr;
	
	LNode *p = head;
	for(int i = 1;i<n;i++){
		LNode *temp = new LNode();
		temp->data = arr[i];
		temp->next = nullptr;
		
		p->next = temp;
		p = temp;
	}
	return head;
}

LNode *reverList(LNode *&head){
	if(head == nullptr || head->next == nullptr)
		return head;
	
	LNode *pre = nullptr,*cur = head;//注意pre的初始值是nullptr,cur是head 
	while(cur != nullptr){
		LNode *last = cur->next;
		cur->next = pre;
		pre = cur;
		cur = last;
	}
	
	head = pre;
	return head;
}


void show(LNode *head){
	LNode *p = head;
	while(p != nullptr)
	{
		printf("%d ",p->data);
		p = p->next;
	}
	puts("");
}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值