栈是一种后进先出的线性表,是最基本的一种数据结构,在许多地方都有应用。 

一、什么是栈

  栈是限制插入和删除只能在一个位置上进行的线性表。其中,允许插入和删除的一端位于表的末端,叫做栈顶(top),不允许插入和删除的另一端叫做栈底(bottom)。对栈的基本操作有 PUSH(压栈)POP (出栈),前者相当于表的插入操作(向栈顶插入一个元素),后者则是删除操作(删除一个栈顶元素)。栈是一种后进先出(LIFO)的数据结构,最先被删除的是最近压栈的元素。栈就像是一个箱子,往里面放入一个小盒子就相当于压栈操作,往里面取出一个小盒子就是出栈操作,取盒子的时候,最后放进去的盒子会最先被取出来,最先放进去的盒子会最后被取出来,这即是后入先出。下面是一个栈的示意图:

 基本数据结构 -- 栈简介(C语言实现)

  

 

二、栈的实现

  由于栈是一个表,因此任何实现表的方法都可以用来实现栈。主要有两种方式,链表实现和数组实现。

2.1 栈的链表实现

  可以使用单链表来实现栈。通过在表顶端插入一个元素来实现 PUSH,通过删除表顶端元素来实现 POP。使用链表方式实现的栈又叫动态栈。动态栈有链表的部分特性,即元素与元素之间在物理存储上可以不连续,但是功能有些受限制,动态栈只能在栈顶处进行插入和删除操作,不能在栈尾或栈中间进行插入和删除操作。

  栈的链表实现代码如下,编译环境是 win10,vs2015:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "windows.h"

struct stack_node {
    int data;
    struct stack_node *next;
};

typedef struct stack_node *PtrToNode;
typedef PtrToNode Stack;

Stack create_stack();
void push_stack(Stack s, int data);
void pop_stack(Stack s);
int top_stack(Stack s);
int stack_is_empty(Stack s);

int main() 
{
    Stack stack = create_stack();        // 新建一个空栈
    int top_data,i;
    // 压栈操作,执行10次
    for (i = 0;i < 10;i++) {
        push_stack(stack, i);
    }
    // 出栈操作,执行1次
    pop_stack(stack);
    // 返回栈顶元素的值
    top_data = top_stack(stack);
    printf("%d\n", top_data);

    system("pause");
}

/* 创建一个空栈 */
Stack create_stack()
{
    Stack S;

    S = (Stack)malloc(sizeof(struct stack_node));
    if (S == NULL)
        printf("malloc fair!\n");
    S->next = NULL;

    return S;
}

/* PUSH 操作 */
void push_stack(Stack s,int data) 
{
    // 新建一个结点,用于存放压入栈内的元素,即新的栈顶
    PtrToNode head_node = (PtrToNode)malloc(sizeof(struct stack_node));
    if (head_node == NULL)
        printf("malloc fair!\n");

    head_node->data = data;            // 添加数据
    head_node->next = s->next;        // 新的栈顶 head_node 的 next 指针指向原来的栈顶 s->next
    s->next = head_node;            // s->next 现在指向新的栈顶
}

/* POP 操作 */
void pop_stack(Stack s) 
{
    PtrToNode head_node = (PtrToNode)malloc(sizeof(struct stack_node));
    if (head_node == NULL)
        printf("malloc fair!\n");

    // 先判断栈是否为空,若栈为空,则不能再进行出栈操作,报错
    if (stack_is_empty(s)) {
        printf("Error! Stack is empty!\n");
    }
    else {
        head_node = s->next;            // head_node 为栈顶
        s->next = head_node->next;        // s->next 指向 head_node->next ,即新的栈顶
        free(head_node);                // 释放原来栈顶元素所占的内存
    }
}

/* 查看栈顶元素 */
int top_stack(Stack s) 
{
    if (stack_is_empty(s)) {
        printf("Error! Stack is empty!\n");
        return 0;
    }
    else {
        return s->next->data;
    }
}

/* 判断栈是否为空 */
int stack_is_empty(Stack s) 
{
    return s->next == NULL;
}
View Code

相关文章:

  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2021-08-18
  • 2021-11-28
  • 2021-07-25
  • 2020-07-16
猜你喜欢
  • 2021-12-15
  • 2021-10-20
  • 2021-12-05
  • 2022-01-04
  • 2021-11-29
  • 2021-09-09
相关资源
相似解决方案