功能说明
代码为顺序栈的相关操作,主要操作为创建链栈、入栈、出栈、获取链栈长度以及打印链栈中的元素等功能。代码由头文件(LinkStack.h)、接口实现(LinkStack.c)和测试文件(main.c)三部分组成。
LinkStack.h
#ifndef __LINKSTACK__
#define __LINKSTACK__
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable:4996)
typedef int Elemtype;
typedef struct LNode
{
Elemtype data;
struct LNode *next;
}LNode,*LinkStack;
LinkStack CreateLinkStack(LinkStack L);
LinkStack Push(LinkStack L, Elemtype x);
int LengthStack(LinkStack L);
LNode* Pop(LinkStack L);
void PrintStack(LinkStack L);
#endif
LinkStack.c
#include"LinkStack.h"
LinkStack CreateLinkStack(LinkStack L)
{
L = (LinkStack)malloc(sizeof(LNode));
if (L == NULL)
{
return NULL;
}
L->next = NULL;
L->data = -1;
return L;
}
LinkStack Push(LinkStack L, Elemtype x)
{
LinkStack temp = (LNode*)malloc(sizeof(LNode));
if (temp == NULL)
{
printf("申请内存失败!\n");
return NULL;
}
temp->data = x;
temp->next = L->next;
L->next = temp;
return L;
}
int LengthStack(LinkStack L)
{
int i = 0;
LinkStack temp = L->next;
while (temp != NULL)
{
i++;
temp = temp->next;
}
return i;
}
LNode* Pop(LinkStack L)
{
LinkStack temp;
if (L->next == NULL)
{
return NULL;
}
temp = L->next;
L->next = temp->next;
return (LNode*)temp;
}
void PrintStack(LinkStack L)
{
LinkStack temp = L->next;
if (L->next == NULL)
{
return;
}
printf("栈中元素为: ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
main.c
#include"LinkStack.h"
int main(int argc, const char* argv[])
{
LinkStack L = NULL;
LNode *temp = NULL;
int len,i;
L = CreateLinkStack(L);
for (i = 0; i < 10; i++)
{
L = Push(L, i);
}
len = LengthStack(L);
printf("栈的长度为%d\n", len);
temp = Pop(L);
printf("出栈元素为%d\n", temp->data);
PrintStack(L);
return 0;
}