数据逆序问题

关于数据逆序问题,当遇到这个问题是我们一般会想到两种解决办法:微笑

1,使用栈先入后出(STL中的stack直接使用);

2.学习过二叉树的对与递归可能比较了解,而第二种就是递归。

下面我们就已链表的逆序输出,做一下展示。(在此我们没有必要将整个链表结构逆序大笑

#include <stdio.h>
#include <stdlib.h>
#include <stack>
struct node 
{
	int data;
	struct node *next;
	
};

struct node *head;   //创建头结点

void ListCreat()  //创建链表
{
	struct node *Node;
	struct node *index;
	
	int i = 0;
	head = (struct node *)malloc( sizeof(struct node) );  //个人喜好每个链表有一个头结点
	index = head;

	while(i < 10)
	{
		Node = (struct node *)malloc(sizeof(struct node));
		Node->data = i;
		Node->next = NULL;
		index->next = Node;
		index = index->next;
		i++;
	}
}

//栈方法
void Listprint1(struct node *head)
{
	struct node *ptr1 = NULL;
	struct node *ptr = head;
	std::stack<struct node *>Stack;

	if(NULL==ptr)
		return;

	while(ptr->next != NULL)    //入栈
	{
		Stack.push(ptr->next);
		ptr= ptr->next;
	}

	while(!Stack.empty())   //出栈
	{
		ptr1= Stack.top();
		printf("%d",ptr1->data);
		Stack.pop();
	}
}

//递归法
void Listprint2(struct node *head)
{
	struct node *ptr = head->next;
	if(NULL == ptr)
		return;
	Listprint2(ptr);
	printf("%d",ptr->data);
}



void main()
{


	struct node *index;
	ListCreat();
	index = head;
	index = index->next;
	while( index != NULL )
	{
		printf("%d\n ", index->data);
		index = index->next;
	}
	printf("--------------------------------------\n");
	//Listprint1(head);
	Listprint2(head);
}
总结:以后不论是面试还是工作当中遇到此类问题是一般运用此两种方法。当然还会有其它方法在此希望大神指导。微笑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值