1. 程式人生 > 其它 >27.1、形態學---開運算、閉運算原理

27.1、形態學---開運算、閉運算原理

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int elemType;
typedef struct linklist
{
    elemType data;
    struct linklist *next;
} node, *linklist;
linklist initLinklist()
{
    linklist s;
    s = (linklist)malloc(sizeof(node));
    s->next = NULL;
    return
s; } int PushLinkStack(linklist s, elemType e) { linklist new; new = (linklist)malloc(sizeof(node)); if (!new) { printf("node is null\n"); return 0; } new->data = e; new->next = s->next; s->next = new; return 1; } void printStack(linklist s) { linklist p
= s->next; if (s->next == NULL) { printf("stack is null\n"); } while (p) { printf("%d<-", p->data); p = p->next; } printf("\n"); } void popLinkStack(linklist s) { linklist p; p = s->next; if (s->next == NULL) { printf(
"當前棧為空\n"); return; } else { s->next = p->next; free(p); p = NULL; } } elemType getLinkTop(linklist s) { linklist p; if (s->next != NULL) { p = s->next; return p->data; } else { printf("stack is null\n"); } } void clearStack(linklist s) { linklist p, q; p = s->next; while (p) { q = p; p = p->next; free(q); q = NULL; } s->next = NULL; s->data = 0; } int main() { elemType e; linklist s; int topElem; s = initLinklist(); s->data = 0; //表示棧當前長度 if (s) { printf("初始化成功\n"); } printf("十次入棧\n"); for (int i = 0; i < 10; i++) { if (PushLinkStack(s, i + 1)) { s->data++; } } printf("當前棧長度為:%d\n", s->data); printf("Linklist:\n"); printStack(s); printf("取棧頂元素:%d\n", getLinkTop(s)); printf("執行四次出棧操作:\n"); for (int i = 0; i < 4; i++) { popLinkStack(s); s->data--; } printf("當前棧長度為:%d\n", s->data); printf("Linklist:\n"); printStack(s); printf("取棧頂元素:%d\n", getLinkTop(s)); printf("清空棧\n"); clearStack(s); printStack(s); return 0; }