用C实现链表倒序

建立链表单元

struct Node{
	int data ;
	Node * next ;
};

打印

void print_list(Node * head){
	if(head){
		printf("%d " , head->data) ;
		print_list(head->next) ;
	}
}

迭代方式

void * reverse_list(Node ** head){
	Node * node_1 , * node_2 , * node_3 ;
	node_1 = *head ;//原地守候
	node_2 = (*head)->next ;//向前走不回头
	while(node_2){//只要还活着
		node_3 = node_2->next ;//到前面探探路
		node_2->next = node_1 ;//蓦然回首
		node_1 = node_2 ;//两情相悦
		node_2 = node_3 ;//再度追随
	}
	(*head)->next = NULL ;
	(*head) = node_1 ;//最后的生还者
}

递归方式

void reverse_list(Node ** head){
	Node * temp = *head ;
	if(temp->next == NULL)
		return ;
	*head = (*head)->next ;
	reverse_list(head) ;
	temp->next->next = temp ;//未来的我爱上我
	temp->next = NULL ;//没得未来了
}

主函数

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

int main(){
	Node * p4 = (Node *)malloc(sizeof(Node)) ;
	p4->data = 4 ; p4->next = NULL ;
	
	Node * p3 = (Node *)malloc(sizeof(Node)) ;
	p3->data = 3 ; p3->next = p4 ;
	
	Node * p2 = (Node *)malloc(sizeof(Node)) ;
	p2->data = 2 ; p2->next = p3 ;
	
	Node * p1 = (Node *)malloc(sizeof(Node)) ;
	p1->data = 1 ; p1->next = p2 ;
	
	
	Node * head = p1 ;
	print_list(head) ;
	printf("\n") ;
	reverse_list(&head) ;
	print_list(head) ;
	
	system("pause");
	return 0 ;
}
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值