头疼的算法与数据结构——链表实现栈

    xiaoxiao2021-03-25  86

    实现栈的功能可以用数组和链表,这里我用链表写了一个栈。

    实现主要思想:

    (1)因为栈时后进先出的,所以我们在使用链表压栈的时候,将要压栈的那个元素放到头节点。 (2)出栈就是删除头节点,因为你后面插入的节点在头节点。

    代码实现:

    #include <stdio.h> #include <stdlib.h> struct node{ int data; struct node *next; }; typedef struct node Node; #define SIZE sizeof(Node) Node* creteNode(int d); void push(Node** h); int addFont(int d,Node** h); void pop(); //创建节点 Node* creteNode(int d) { Node* pn=(Node*)malloc(SIZE); pn->data=d; pn->next=NULL; return pn; } //压栈 void push(Node** h) { Node* pn=NULL; Node* p=NULL; int d; printf("请输入数据\n"); scanf("%d",&d); pn=creteNode(d); *h=pn; p=*h; while(1) { printf("请输入数据\n"); scanf("%d",&d); if(d==0) break; addFont(d,h); } } //头插法 int addFont(int d,Node** h)//修改头节点 传入二级指针 { Node* pn=NULL; pn=creteNode(d); pn->next=*h; *h=pn; } //出栈 void pop(Node** h) { Node* pd=*h; *h=pd->next; printf("%d:出栈\n",pd->data); free(pd); pd=NULL; } //打印栈中的元素 void print(Node* h) { printf("list:\n"); while(h) { printf("%d ",h->data); h=h->next; } printf("\n"); } int main() { Node* head=NULL; push(&head); print(head); pop(&head); print(head); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-35900.html

    最新回复(0)