链表反转的C语言实现(迭代法和递归法)—— 图文详解

实现功能:

  • 原链表:head->0->1->2->3->4->NULL
  • 反转后:head->4->3->2->1->0->NULL

1.迭代法

1.得到链表后,先定义两个指针。current指向头结点;prev指向NULL。

1

2.执行操作:

  • 定义临时指针next储存当前节点指向的下一个节点的地址。

    struct node* next = current->next;
    
  • 把prev的值赋给当前节点的下一个地址值(头节点指向NULL,其他节点指向上一个节点)。

    current->next = prev;
    
  • 把当前节点地址给prev。

    prev = current;
    
  • next值赋给current,current指针向后一个节点移动。

    current = next;
    

2

3.不断重复上一步的操作,当前节点指向上一个节点后current指针和prev指针继续后移,不断迭代。

3

44.直到current指针移到NULL时prev指向最后一个节点,此时链表反转完成,将prev返回为链表头head。

5

代码:

struct node* reverse1(struct node* head)
{
	struct node* prev = NULL;
	struct node* current = head;
	while(current){
		struct node* next = current->next;
		current->next = prev;
		prev = current;
		current = next;
	}
	return prev;
}

2.递归法

  • 传入头结点的值后不断调用自己,下一个函数压栈,传入的值依次为下一个节点的地址。当压顶的函数参数指向NULL时递归结束,函数逐次释放,执行后面的代码:
    此时最顶的函数已经释放,返回的指针即为链表头,声明head保存,下面每个函数的指针指向节点都把下一个节点的next指向自己并将当前的next指向空,实现链表反转,直到第一个函数结束返回head。

递归
代码:

struct node* reverse2(struct node* p)
{
	if(p->next == NULL){   //递归结束
		return p;
	}
	struct node* head = reverse2(p->next); //保存链表头的值
	p->next->next = p;
	p->next = NULL;
	return head;

}

运行程序:

  • 运用以上的两种方法实现链表两次反转
#include <stdio.h>
#include <stdlib.h>

/*定义结构体*/
struct node
{
	int data;
	struct node *next;
};

/*头插法创建链表*/
struct node* insert(struct node *head,int data)
{
	struct node *new = head;
    new = (struct node *)malloc(sizeof(struct node));
    new->data = data;

        if(head == NULL){
                head = new;
        }else{
                new->next = head;
                head = new;
        }

        return head;

}

/*遍历链表*/
void printLink(struct node *head)
{
	printf("head->");
	while(head != NULL){
		printf("%d->",head->data);
		head = head->next;
	}
	printf("NULL");
	putchar('\n');
}

/*迭代法反转*/
struct node* reverse1(struct node* head)
{
	struct node* prev = NULL;
	struct node* current = head;
	while(current){
		struct node* next = current->next;
		current->next = prev;
		prev = current;
		current = next;
	}
	return prev;
}

/*递归法反转*/
struct node* reverse2(struct node* p)
{
	if(p->next == NULL){
		return p;
	}
	struct node* head = reverse2(p->next);
	p->next->next = p;
	p->next = NULL;
	return head;

}


int main()
{	
	int n=5;
	struct node *head = NULL;

	printf("Link:\n");  //随便创建一个链表
	while(n--){
		head = insert(head,n);
	}
	printLink(head);
	
	printf("reverse1:\n");//迭代法反转
	head = reverse1(head);
	printLink(head);
	
    printf("reverse2:\n");//递归法反转
    head = reverse2(head);
    printLink(head);

	return 0;
}	

运行结果:
运行

  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

money的大雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值