关于栈的链式存储结构

之前在创建栈的链式存储结构时,想当然误以为栈的top指针会指向链表的尾结点,在创建链表结构时的写法误写为:

 for(j=0;j<i;j++){
        temp=(struct Node*)malloc(sizeof(struct Node));
        printf("Input:");
        scanf("%c",&a);
        getchar();
        temp->data=a;
        temp->next=NULL;
        if(!head){
            head=tail=temp;
        }
        else{
            tail->next=temp;
            tail=temp;
        }

    }

但创建链表栈是应该是尾结点针为栈底,top指针应该指向头结点,如图:


所以栈的创建、增加、删除结点代码如下所示:

struct Node* create(){
    struct Node*temp=0;
    temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data='a';
    temp->next=NULL;
    s.top=temp;
    s.count=-1;
    return temp;
}
bool push(char a,struct linkstack* m){
     struct Node* temp=0,*tail=0;
     temp=(struct Node*)malloc(sizeof(struct Node));
     temp->data=a;
     temp->next=m->top;
     m->top=temp;
     m->count++;
     return true;
}
bool pop(struct linkstack* m){
    struct Node *p=0;
    if(m->count==-1)
        return false;
    else{


        p=m->top;
        m->top=m->top->next;
        free(p);
        m->count--;
        return true;
    }
}
void read(struct linkstack *s){
    struct Node* temp=s->top;
    while(temp){
        printf("%c",temp->data);
        temp=temp->next;
    }

}

这样便巧妙地避免了对头结点的记录问题,top就是头结点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值