链表的建立、输出、非递归反转、递归反转

链表的建立、输出、非递归反转、递归反转

代码如下:

#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <string> 
#include <string.h> 
#include <fstream> 
#include <map> 
#include <iomanip> 
#include <cmath>
#include <set>
#include <stdio.h>
#include <queue>

using namespace std; 

const int MAX = 0x7FFFFFFF; 
const int MIN = 0x80000000; 

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

//功能:创建链表
//输入:头结点
//返回值:-1代表创建失败,1代表创建成功
int createList(Node** head)
{
	int a, count = 0;
	Node *cur, *pre;
	//0为终止符
	while(cin >> a && a != 0)
	{
		if(count == 0)
		{
			*head = (Node*)malloc(sizeof(Node));
			if(*head == NULL)
				return -1;
			(*head)->value = a;
			(*head)->next = NULL;
			cur = pre = *head;
		}
		else
		{
			cur = (Node*)malloc(sizeof(Node));
			if(cur == NULL)
				return -1;
			cur->value = a;
			cur->next = NULL;
			pre->next = cur;
			pre = cur;
		}
		count++;
	}
	return 1;
}

//功能:打印链表
//输入:链表头结点
//返回值: -1代表链表为空,1代表打印成功
int printList(Node* head)
{
	if(head == NULL)
		return -1;
	while(head != NULL)
	{
		cout << head->value << " ";
		head = head->next;
	}
	cout << endl;
	return 1;
}

//非递归反转链表
//输入:二级指针的头结点
//返回值:-1表示链表为空,1代表反转成功
//参数中的头结点为二级指针,函数完成之后,head指向反转后的结点
int reverseListNotRecursion(Node** head)
{
	Node* cur, *pre = *head;
	if(*head == NULL)
		return -1;
	while(pre->next != NULL)
	{
		cur = pre->next;
		pre->next = cur->next;
		cur->next = *head;
		*head = cur;
	}
	return 1;
}

//递归反转链表
//输入:头结点,待反转结点
//返回值:当前反转的结点,已插入尾部
//返回为参数中的引用,即反转后的头结点
Node* reverseListRecursion(Node** head, Node* p)
{
	Node* remain;
	if(p == NULL || p->next == NULL)
	{
		*head = p;
		return p;//返回最后一个结点
	}
	remain = reverseListRecursion(head, p->next);
	remain->next = p;
	p->next = NULL;
	return p;
}

int main()
{
	Node *head = NULL;

	//建立链表
	//假设创建链表中数依次为:1,2,3,4,5
	createList(&head);

	//输出创建之后的链表
	//输出1 2 3 4 5 
	printList(head);
	
	//非递归反转链表
	reverseListNotRecursion(&head);
	//输出5 4 3 2 1
	printList(head);

	//递归反转链表
	reverseListRecursion(&head, head);
	//输出1 2 3 4 5 
	printList(head);

	system("pause");
	return 0;
}


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值