链表的倒序查找

我所使用的方法在输入的时候是使用一个栈存储所有的数据,利用的是其先进后出的数据结构。
当然,用一个数组也是可以的= =,而且我觉得还可以保存数据,而用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\n");
        exit(1);
    }
    
    head = NULL;
    
    Node *p1,*p2;
    p1 = p2 = (Node *)malloc(LEN);
    if(p1 == NULL || p2 == NULL)
    {
        printf("Overflow\n");
        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\n");
            exit(1);
        }
        
        scanf("%d",&p1 -> data);
    }
    p2 -> next = NULL;
    
    return head;
}

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

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

int main()
{
    Node *head;
    head = Node_Creat();
    
    Node_Print(head);
    
    int num;
    scanf("%d",&num);
    printf("Reverse Found num: %d\n",num);
    
    Node_ReverseFound(num);
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值