鏈棧的基本操作 C語言


#include<stdio.h>
#include<stdlib.h>
typedef char ElementType;
typedef struct node* LinkStack;
struct node {
    ElementType data;
    LinkStack next;
};
//初始化
void InitLinkStack(LinkStack *L) {
    (*L) = NULL;
}
//入棧
void PushStack(LinkStack *L, ElementType x) {
    LinkStack s;
    s = (LinkStack)malloc(sizeof(struct node));
    s->data = x;
    s->next = (*L); //L是棧頂元素
    (*L) = s;  //s成為新的棧頂元素
}
//出棧
void PopStack(LinkStack *L, ElementType *x) {
    if ((*L)->next == NULL) {
        printf("空棧");
    }
    else {
        LinkStack p;
        *x = (*L)->data;
        p = (*L);  //標記棧頂
        (*L) = (*L)->next;
        free(p); //出棧
    }
}
void PrintNode(LinkStack L) {
    while (L != NULL) {
        printf("%c", L->data);
        L = L->next;
    }
    printf("\n");
}
int main() {
    LinkStack s;
    ElementType c;
    ElementType* y;
    y = &c; 
    InitLinkStack(&s);
    printf("入棧元素為:\n");
    scanf("%c", &c);
    while (c != '\n') {
        PushStack(&s, c);
        scanf("%c", &c);
    }
    PrintNode(s);
    PopStack(&s, y);
    printf("出棧元素為:%c\n", *y);
    printf("棧中剩余元素為:\n");
    PrintNode(s);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM