注册 登录
编程论坛 C语言论坛

请教关于栈的问题。。

温酒斩化腾 发布于 2018-02-23 18:10, 1277 次点击
#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后栈内的数据不变呢?
1 回复
#2
loboce2018-02-23 23:06
AllPath()调用之前,栈内都只有一个数据,调用后,函数体内,无论先调用Print(),或是先调用findval(),都会第pop();就把栈内唯一的数据弹出栈。这个时候,栈是空的了,栈顶跟栈底一样。也就是你说的栈内数据不变了。
1