記錄下剛學(xué)的棧
#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 createStack(); //初始化棧
void pushStack(Stack s, int data); //壓棧
void popStack(Stack s); //出棧
void printStack(Stack s); //打印棧
void getStackTop(Stack s); //獲取棧頂
int main()
{
Stack S = createStack();
int i = 0, j = 0;
for (; i < 10; i++)
{
pushStack(S, i);
}
for (; j < 10; j++)
{
popStack(S);
}
// PrintStack(S);
return 0;
}
Stack createStack()
{
Stack s;
s = (Stack)malloc(sizeof(struct stack_node));
if (s == NULL)
{
printf("申請空間失敗");
}
s->next = NULL;
return s;
}
//判斷是否為空
int isEmtry(Stack s)
{
return s->next ==NULL?0:1;
}
void pushStack(Stack s, int data)
{
//新的棧頂
PtrToNode head = (PtrToNode)malloc(sizeof(struct stack_node));
if (head == NULL)
{
printf("push時申請空間失敗");
}
//push順序 相當于s->null之間插入head s->head->null
head->data = data; //賦值
head->next = s->next;
s->next = head;
}
void popStack(Stack s)
{
PtrToNode head = (PtrToNode)malloc(sizeof(struct stack_node));
if (head == NULL)
printf("申請空間失敗!\n");
if (!isEmtry(s))
{
printf("棧為空话速,無法操作");
}
else
{
head = s->next; // head_node 為棧頂
s->next = head->next; // s->next 指向 head_node->next ,即新的棧頂
printf("出棧結(jié)果%d", head->data);
free(head); // 釋放原來棧頂元素所占的內(nèi)存
}
}
//打印棧值
void printStack(Stack s)
{
PtrToNode aim = s->next;
while (aim)
{
printf("%d", aim->data);
aim = aim->next;
}
return;
}
void getStackTop(Stack s)
{
PtrToNode top = s->next;
!isEmtry(s) ? printf("棧為空") : printf("棧頂數(shù)字為:/d", top->data);
return;
}