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("");
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/82953082