| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1300 人关注过本帖
标题:请教关于栈的问题。。
只看楼主 加入收藏
温酒斩化腾
Rank: 1
等 级:新手上路
帖 子:32
专家分:0
注 册:2017-3-28
结帖率:72.73%
收藏
 问题点数:0 回复次数:1 
请教关于栈的问题。。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>

using namespace std;


int map[6][6] = {
    { 0, 2, 10, 5, 3, -1 },
    { -1, 0, 12, -1, -1, 10 },
    { -1, -1, 0, -1, 7, -1 },
    { 2, -1, -1, 0, 2, -1 },
    { 4, -1, -1, 1, 0, -1 },
    { 3, -1, 1, -1, 2, 0 }
};

stack<int> s;

void Print(stack<int> s)
{
    while (!s.empty())
    {
        cout << s.top() << " ";
       s.pop();
    }
    cout << endl;
}
bool findval(stack<int> s, int val)
{
    while (!s.empty())
    {
        if (s.top() == val)
        {
            return true;
        }
        s.pop();
    }
    return false;
}

void AllPath(int start, int end)
{
    if (start == end)
    {
        Print(s);
        s.pop();
        return;
    }

    for (int i = 0; i < 6; i++)
    {
        if (map[start][i] != -1 && start != i && findval(s, i) == false)
        {
            s.push(i);
            AllPath(i, end);
        }
    }

    //这一步很重要!对于start节点遍历所有连接,如果遍历完,就要把stack中的start节点pop掉,否则会无限递归
    s.pop();
}


int main()
{
    int X = 0, Y = 4;

    s.push(X);

    while (!s.empty())
    {
        AllPath(X, Y);
    }

    return 0;
}
为什么这两个地方pop后栈内的数据不变呢?
搜索更多相关主题的帖子:  include stack int start 
2018-02-23 18:10
loboce
Rank: 2
等 级:论坛游民
威 望:1
帖 子:26
专家分:96
注 册:2014-6-7
收藏
得分:0 
AllPath()调用之前,栈内都只有一个数据,调用后,函数体内,无论先调用Print(),或是先调用findval(),都会第pop();就把栈内唯一的数据弹出栈。这个时候,栈是空的了,栈顶跟栈底一样。也就是你说的栈内数据不变了。
2018-02-23 23:06
快速回复:请教关于栈的问题。。
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014246 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved