转载

链栈

链栈

具体原理参见链栈的实现
#include<stdio.h>

struct ListNode{

    int value;
    struct ListNode *next;
};
typedef struct ListNode* ListNodePoint;

void push(ListNodePoint &stack, int value) {
    ListNode *p = new ListNode;
    p->value = value;

    p->next = stack;
    stack = p;
}

bool pop(ListNodePoint &stack) {
    if(stack == NULL) return false;

    ListNode *p = stack;
    stack = stack->next;
    delete p;
    return true;
}

int getTop(ListNodePoint &stack){
    if(stack == NULL) return -1;
    else return stack->value;
}

int main() {
    ListNode *stack = NULL;

    push(stack, 1);
    push(stack, 2);
    push(stack, 3);
    push(stack, 4);
    push(stack, 5);
    push(stack, 6);

    while(stack != NULL) {
        printf("%d ", getTop(stack));
        pop(stack);
    }
}
正文到此结束
本文目录