注册 登录
编程论坛 数据结构与算法

刚刚上完链式栈课,凭着理解写了个入栈的代码,调试不运行,求指教

Onesaber 发布于 2013-10-20 22:02, 538 次点击
程序代码:
#include <iostream>
using namespace std;
struct node
{
    node *next;
    int data;
};
class link
{
private:
    node *head;
public:
    link(){head=NULL;}
    void cut(int i);
    void out();
};
void link::cut(int i)
{
    node *s;
    s=new node;
    s->next=head->next;
    s->data = i;
    head->next=s;
}

void link::out()
{
    node *p;
    p = head;
    while(p->next==NULL)
    {
        p=p->next;
        cout<<p->data<<endl;
    }
}

void main()
{
    link A;
    A.cut(1);
        A.cut(2);
    A.cut(3);
    A.cut(4);
    A.cut(5);
    A.cut(6);
    A.cut(7);
    A.out();
}
3 回复
#2
yuccn2013-10-21 16:32
class link
{
private:
    node *head;
public:
    link(){head=NULL;}
    void cut(int i);
    void out();
};
void link::cut(int i)
{
    node *s;
    s=new node;
    s->next=head->next; 刚刚开始的时候 ,head 是NULL的,head->next 这样就足够他崩溃啦
    s->data = i;
    head->next=s;
}

link(){head=NULL;} 把这个改成
link()
{
head=new node;
head->next = NULL;
}
试试
#3
yuccn2013-10-21 16:33
void link::out()
{
    node *p;
    p = head;
    while(p->next==NULL)这个改成 while(p->next!=NULL)
    {
        p=p->next;
        cout<<p->data<<endl;
    }
}
#4
Onesaber2013-10-21 19:43
回复 3楼 yuccn
成功运行了非常感谢指教,但是运行时只输出了最后一个入栈的元素,能帮我看看嘛?
1