| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1256 人关注过本帖
标题:c语言实现链栈的进栈和出栈怎么错了??
取消只看楼主 加入收藏
dlfhcg
Rank: 1
等 级:新手上路
帖 子:13
专家分:5
注 册:2010-9-23
结帖率:100%
收藏
已结贴  问题点数:2 回复次数:1 
c语言实现链栈的进栈和出栈怎么错了??

    typedef struct linkstack
{
    int data;
    struct linkstack *next;
}ST;

#define LEN sizeof(ST)
#define NULL 0
#include <stdio.h>
#include <malloc.h>
void main()
{   

    int num[5],i;
    ST *top, *push(ST *top,int x);
    int pop(ST *top);
    top=(ST *)malloc(LEN);
    top=NULL;
    for(i=0;i<5;i++)
    {
        printf("Please input the %d number:",i+1);
        scanf("%d",&num[i]);
    }
    printf("The push numbers:\n");
    for(i=0;i<5;i++)
        printf("%d\t",num[i]);
    for(i=0;i<5;i++)
    top=push(top,num[i]);
    for(i=0;i<5;i++)
    printf("%d",pop(top));
}



ST *push(ST *top,int x)
{   
    ST *p;
    p=(ST *)malloc(LEN);
    p->data=x;
    p->next=top;
    top=p;
    return top;
}


int pop(ST *top)
{
    ST *p;
    int num;
        p=top;
        num=top->data;
        top=top->next;
        free(p);
        return num;
   
}
搜索更多相关主题的帖子: c语言 
2010-09-24 00:58
dlfhcg
Rank: 1
等 级:新手上路
帖 子:13
专家分:5
注 册:2010-9-23
收藏
得分:0 
谢谢楼上的回答。
你说的没错,pop改变了top指针但没有返回。
你的方法也行的通。
typedef struct linkstack
{
    int data;
    struct linkstack *next;
}ST;

#define LEN sizeof(ST)
#define NULL 0
#include <stdio.h>
#include <malloc.h>
void main()
{   

    int num[5],i;
    ST *top=NULL,**p=NULL, *push(ST *top,int x);
    int pop(ST **head);
    for(i=0;i<5;i++)
    {
        printf("Please input the %d number:",i+1);
        scanf("%d",&num[i]);
    }
    printf("The push numbers:\n");
    for(i=0;i<5;i++)
        printf("%d\t",num[i]);   
    printf("\n");
    for(i=0;i<5;i++)
    top=push(top,num[i]);
    *p=top;
    printf("The pop numbers:\n");
    for(i=0;i<5;i++)
    printf("%d\t",pop(p));
}



ST *push(ST *top,int x)
{   
    ST *p;
    p=(ST *)malloc(LEN);
    p->data=x;
    p->next=top;
    top=p;
    return top;
}


int pop(ST **head)
{
    ST *p;
    int num;
        p=*head;
        num=p->data;
        *head=p->next;
        free(p);
        return num;
   
}
您看这个程序为什么在vc中运行时显示“内存不能为written”??
谁能告诉我哪里错了?

有时睡觉是件好工作,黑白颠倒的大学生活倒省了不少饭钱,省钱就是赚钱。
2010-09-24 17:01
快速回复:c语言实现链栈的进栈和出栈怎么错了??
数据加载中...
 
   



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

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