数据结构:单向链表反转(C/C++)

单向链表在数据结构中比较常见,要求实现单向链表的反转,如下图所示:
反转前:
在这里插入图片描述
反转后:
在这里插入图片描述
C++代码如下:

#include <stdio.h>
#include <stdlib.h>

struct list{
	int var;
	struct list *next;
};
//反转单向链表
void reversal(struct list* &head)
{
	struct list *p1,*pre,*after;
	p1=head;
	pre=head;
	head=head->next;
	while(head){
		after=head->next;
		head->next=pre;
		pre=head;
		if(after == NULL){
			break;
		}
		head=after;
	}
	p1->next = NULL;
}

int main(){
	int a[]={1,5,7,8,9,2,4,6,8,9,10,13,16,0};
	struct list *head,*p1,*p2;
	//创建单向链表
	head=(struct list *)malloc(sizeof(struct list));
	head->var=a[0];
	head->next=NULL;
	p1=head;
	for(int i=1;i<sizeof(a)/sizeof(int);i++){	
		head->next=(struct list *)malloc(sizeof(struct list));
		head=head->next;
		head->var=a[i];
		head->next=NULL;		
	}
	head=p1;
	//打印单向链表
	while(p1){
		printf("%2d ",p1->var);
		p1=p1->next;
	}
	printf("\n");
	//反转单向链表
	reversal(head);
	//打印反转后的单向链表
	p1=head;
	while(p1){
		printf("%2d ",p1->var);
		p1=p1->next;
	}
	printf("\n");
	//释放链表内存空间
	p1=head;
	while(p1){
		p2=p1->next;
		free(p1);
		p1=p2;
	}
	return 0;
}

由于函数void reversal(struct list* &head)的语法只能用于C++语言,C语言的语法不能识别,要改成C语言的语法的话,可以用指向指针的指针来传递,void reversal(struct list **head),这样就能适应这个算法从而改变head首地址的指向。

C语言代码如下:

#include <stdio.h>
#include <stdlib.h>

struct list{
	int var;
	struct list *next;
};

void reversal(struct list **head)
{
	struct list *p1,*pre,*after,*headNew;
	headNew=*head;
	p1=headNew;
	pre=headNew;
	headNew=headNew->next;
	while(headNew){
		after=headNew->next;
		headNew->next=pre;
		pre=headNew;
		if(after == NULL){
			break;
		}
		headNew=after;
	}
	p1->next = NULL;
	*head=headNew; 
}

int main(){
	int a[]={1,5,7,8,9,2,4,6,8,9,10,13,16,0};
	struct list *head,*p1,*p2;
	//创建单向链表
	head=(struct list *)malloc(sizeof(struct list));
	head->var=a[0];
	head->next=NULL;
	p1=head;
	for(int i=1;i<sizeof(a)/sizeof(int);i++){	
		head->next=(struct list *)malloc(sizeof(struct list));
		head=head->next;
		head->var=a[i];
		head->next=NULL;		
	}
	head=p1;
	//打印单向链表
	while(p1){
		printf("%2d ",p1->var);
		p1=p1->next;
	}
	printf("\n");
	//反转单向链表
	reversal(&head);
	//打印反转后的单向链表
	p1=head;
	while(p1){
		printf("%2d ",p1->var);
		p1=p1->next;
	}
	printf("\n");
	//释放链表内存空间
	p1=head;
	while(p1){
		p2=p1->next;
		free(p1);
		p1=p2;
	}
	
	return 0;
}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kaixian2003

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值