反转单链表--迭代和递归分别实现

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

typedef struct node
{
	int value;
	struct node *next;
}Listnode;

Listnode* CreateList(Listnode *head)//建立链表
{
	if(head == NULL)
		return NULL;
	head = (Listnode*)malloc(sizeof(Listnode));
	head->value = 1;
	head->next = NULL;
	int i;
	Listnode *p = head;
	Listnode *q;
	for(i=2;i<10;i++)
	{
		q = (Listnode*)malloc(sizeof(Listnode));
		q->value = i;
		p->next = q;
		q->next = NULL;
		p = q;
	}
	printf("链表节点为:\n");
	p = head;
	while(p)
	{
		printf("%d\t",p->value);
		p = p->next;
	}
	printf("\n");
	return head;

}

Listnode * ReverseList(Listnode* head)//迭代法
{
	if(head == NULL)
		return NULL;
	Listnode *prve, *current,*temp;
	current = head;
	prve = NULL;
	while(current->next)
	{
		temp = current->next;
		current->next = prve;
		prve = current;
		current = temp;
	}
	current->next = prve;
	return current;
}

Listnode *ReverseList_recursive(Listnode *head)//递归法
{
	if(head == NULL)
		return NULL;
	Listnode *temp,*current,*head_reverselist;
	if(head->next == NULL)
		return head;
	else
	{
		current = head;
		temp = current->next;
		head_reverselist = ReverseList_recursive(temp);//返回最后一个节点,也就是反转后的头结点
		temp->next = current;
		current->next = NULL;
	}
	return head_reverselist;
}

void PrintList(Listnode *head)
{
	if(head == NULL)
		return;
	printf("反转后的链表节点为:\n");
	while(head)
	{
		printf("%d\t",head->value);
		head = head->next;
	}
	printf("\n");
}

int main()
{
	Listnode *head;
	head = CreateList(head);
	head = ReverseList(head);//反转一次
	printf("迭代方法:\n");
	PrintList(head);
	head = ReverseList_recursive(head);//反转第二次,恢复原状
	printf("递归方法:\n");
	PrintList(head);
	return 0;
}

结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值