链表的倒序查找

我所使用的方法在输入的时候是使用一个栈存储所有的数据,利用的是其先进后出的数据结构。
当然,用一个数组也是可以的= =,而且我觉得还可以保存数据,而用stack的话操作比较麻烦。

#include <cstdio>
#include <iostream>
#include <stack>
#include <stdlib.h>
#define LEN sizeof(Node)
using namespace std;

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

stack<int> s;

int tot = 0;

Node *Node_Creat()
{
	Node *head;
	head = (Node *)malloc(LEN);
	if(head == NULL)
	{
		printf("Overflow
");
		exit(1);
	}
	
	head = NULL;
	
	Node *p1,*p2;
	p1 = p2 = (Node *)malloc(LEN);
	if(p1 == NULL || p2 == NULL)
	{
		printf("Overflow
");
		exit(1);
	}
	
	scanf("%d",&p1 -> data);
	while(p1 -> data >= 0)
	{
		tot++;
		
		s.push(p1 -> data);
		
		if(head == NULL)
		{
			head = p1;
		}
		else
		{
			p2 -> next = p1;
		}
		
		p2 = p1;
		
		p1 = (Node *)malloc(LEN);
		if(p1 == NULL)
		{
			printf("Overflow
");
			exit(1);
		}
		
		scanf("%d",&p1 -> data);
	}
	p2 -> next = NULL;
	
	return head;
}

void Node_Print(Node *head)
{
	if(head == NULL)
	{
		printf("EMPTY!
");
		return ;
	}
	
	Node *p = head;
	while(p != NULL)
	{
		printf("%d ",p -> data);
		p = p -> next;
	}
	printf("
");
}

void Node_ReverseFound(int num)
{
	int i;
	int data = 0;
	
	if(num > tot)
	{
	    printf("NOT FOUND
");	
	}
	
	for(i = 1; i < num; i++)
	{
		s.pop();
	}
	
	printf("%d
",s.top());
}

int main()
{
	Node *head;
	head = Node_Creat();
	
	Node_Print(head);
	
	int num;
	scanf("%d",&num);
	printf("Reverse Found num: %d
",num);
	
	Node_ReverseFound(num);
	
	return 0;
}
原文地址:https://www.cnblogs.com/qq952693358/p/5507005.html