数据逆序问题

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

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);
}
总结:以后不论是面试还是工作当中遇到此类问题是一般运用此两种方法。当然还会有其它方法在此希望大神指导。 微笑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答这个问题逆序数据建立链表的基本思路是从后往前遍历数据,每次新建一个节点,并将其插入到链表的头部,最终得到的链表即为逆序链表。 具体实现步骤如下: 1. 定义节点结构体,包含数据域和指针域。 2. 定义链表头节点指针,初始化为空。 3. 从后往前遍历数据,每次新建一个节点并赋值,然后将其插入到链表的头部。 4. 循环结束后,链表头节点指针指向新链表的头节点。 下面是一个示例代码: ```c++ #include <iostream> using namespace std; // 定义节点结构体 struct ListNode { int val; ListNode* next; ListNode(int x): val(x), next(NULL) {} }; // 逆序建立链表 ListNode* reverseList(int arr[], int n) { ListNode* head = NULL; for(int i = n - 1; i >= 0; i--) { ListNode* node = new ListNode(arr[i]); node->next = head; head = node; } return head; } // 输出链表 void printList(ListNode* head) { while(head) { cout << head->val << " "; head = head->next; } cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(int); ListNode* head = reverseList(arr, n); printList(head); return 0; } ``` 在上面的示例代码中,我们定义了一个逆序建立链表的函数 `reverseList`,它接收一个数组和数组长度作为参数,返回新链表的头节点指针。我们还定义了一个输出链表的函数 `printList` 来验证建立的链表是否正确。最后在主函数中调用这两个函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值