栈顶用来做插入和删除操作,而单链表有个头指针,并且栈顶指针也是必须的,所以将它们合二为一,将栈顶放在单链表的头部,由于有了栈顶在头部,单链表中比较常用的头节点也没什么意义了,因此一般来说链栈不需要头结点,链栈为空也就是top=NULL
链栈数据结构:
typedef struct {
StackElemType data;
struct StackNode *next;
}StackNode;
typedef struct {
StackNode *top;
int count;
}LinkStack;
创建链栈,都在栈顶头指针处添加一个结点,然后指针指向新添加的结点,写了半天都才达到将添加结点弄完了,明天继续完善
继续搞完,栈只能顶进行插入和删除,比起链表就单调多了
#include <stdio.h>
#include <malloc.h>
typedef struct {
int data;
struct StackNode *next;
}StackNode;
typedef struct{
int count;
StackNode *top;
}LinkStack;
int InitStack(LinkStack *L){
L->top = (StackNode *)malloc(sizeof(StackNode));
L->top = NULL;
L->count = 0;
return 0;
}
/*
int InitNode(StackNode *N){
static int k = 0;
N->data = k;
}
*/
int PushStack(LinkStack *L, StackNode *n){
static int k = 1;
n->data = k;
n->next = L->top;
L->top = n;
++L->count;
++k;
return 0;
}
int PopStack(LinkStack *L){
L->top = L->top->next;
–L->count;
return 0;
}
int main(){
LinkStack *L;
L = (LinkStack *)malloc(sizeof(LinkStack));
InitStack(L);
StackNode *n1, *n2, *n3, *n4, *n5;
n1 = (StackNode *)malloc(sizeof(StackNode));
n2 = (StackNode *)malloc(sizeof(StackNode));
n3 = (StackNode *)malloc(sizeof(StackNode));
n4 = (StackNode *)malloc(sizeof(StackNode));
n5 = (StackNode *)malloc(sizeof(StackNode));
PushStack(L, n1);
PushStack(L, n2);
PushStack(L, n3);
PushStack(L, n4);
PushStack(L, n5);
PopStack(L);
PopStack(L);
int i;
for (i = 0; i < L->count; i++){
printf(“%d\n”, L->top->data);
L->top = L->top->next;
}
return 0;
}
最后居然有三个警告:
warning C4133: ‘=’ : incompatible types – from ‘StackNode *’ to ‘StackNode *’
warning C4133: ‘=’ : incompatible types – from ‘StackNode *’ to ‘StackNode *’
warning C4133: ‘=’ : incompatible types – from ‘StackNode *’ to ‘StackNode *’
通过cygwin里,gcc再编译了一把,的确有警告,坑爹的中文翻译
Source.c: 在函数‘PushStack’中:
Source.c:31:10: 警告:从不兼容的指针类型赋值 [默认启用]
n->next = L->top;
^
Source.c: 在函数‘PopStack’中:
Source.c:39:9: 警告:从不兼容的指针类型赋值 [默认启用]
L->top = L->top->next;
^
Source.c: 在函数‘main’中:
Source.c:69:10: 警告:从不兼容的指针类型赋值 [默认启用]
L->top = L->top->next;
终于解决:
网上搜了下,很多都是下面说法:
定义了一个结构体,定义了一个结构体的指针,在进行动态内存分配的时候,出现了如题所示的报错,
LNode *new_Node;
new_Node=(struct LNode *)malloc(sizeof(LNode));
将动态内存分配的形式改为new_Node=(LNode *)malloc(sizeof(LNode));之后,没有出现报错。
可是我在malloc的时候,也没有带上struct呀,猛地一看定义的node结构体,恍然大悟,node的struct定义时没有和next保持一致,修改成下面这样,警告就没了:
typedef struct StackNode{
int data;
struct StackNode *next;
}StackNode;