链式栈

创建栈是重要部分,还是需要把结构体栈生成栈变量,再用栈指针进行操作

错误写法!!!!!!!!!!!:

错误之处:

1.初始化栈必须被分配空间成为变量,不能只是一个指针

2.初始化栈时,next没有置空,导致链表的结尾不为空(插入元素之后,结尾依旧不为空,因为不为空的地方赋给了新节点),影响到了结尾判断

正确的写法参照:

#include<stdio.h>
#include<stdlib.h>//malloc的库
//现有花为,再有天。先有链表再有栈
//以下是节点定义,链表的创建,节点的创建,节点的插入,打印

//节点定义
struct Node
{
int data;
struct Node* next;
};
//链表创建(头节点创建)
struct Node* createList()
{
struct Node* headNode;
headNode=(struct Node*)malloc(sizeof(struct Node));
headNode->next=NULL;//这一句一定要有,不然节点插入中newNode->next=headNode->next完成后,链表的结尾不为空
return headNode;    
}
//节点创建(可以方便节点插入)
struct Node* createNode(int data)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
//节点插入
void insertNodeByHead(struct Node* headNode,int data)
{
struct Node* newNode=createNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
}

//节点删除(这里不是指定节点,因为是栈的链表所以为第一个节点)
void deleteNodeFirst(struct Node* headNode)
{
struct Node* deleteNode=headNode->next;
headNode->next=deleteNode->next;
free(deleteNode);
}

//链表遍历
void printList(struct Node* headNode)
{
struct Node* pmove;
pmove=headNode->next;
while(pmove)
{
printf("%d ",pmove->data);
pmove=pmove->next;//栈用在这里结束不了
}

free(pmove);
}

//栈的东西(创建栈指向链表进行栈操作)
struct stack
{
int stackLength;
struct Node* stackTop;
};

//栈创建
struct stack* createStack()
{
struct stack* st;
st=(struct stack*)malloc(sizeof(struct stack));
st->stackLength=0;
st->stackTop=createList();
return st;
}

//栈元素插入
void push(struct stack* st,int data)
{
    insertNodeByHead(st->stackTop,data);
    st->stackLength+=1;
}
//元素删除
void pop(struct stack* st)
{
deleteNodeFirst(st->stackTop);
st->stackLength-=1;
}
//获取栈顶元素
int Top(struct stack* st)
{
    if(st->stackLength==0)
    return NULL;
    else
return st->stackTop->next->data;
}
//打印栈
void printStack(struct stack* st)
{
printList(st->stackTop);
printf("
");
printf("The length of stack is:%d
",st->stackLength);
}

int main()
{
struct stack *st=createStack();
push(st,1);
push(st,2);
push(st,3);

printStack(st);
printf("The top is: %d 

",Top(st));
pop(st);
printStack(st);
printf("The top is: %d 
",Top(st));

    
return 0;
}

结果显示:

 温故知新:

void insertNode(struct stack* st,int data){
struct node* newNode=createNode(data);
if(st->top==NULL){
st->top=newNode;
}
else{
newNode->next=st->top;//特别注意这里是st->top,而不是st->top->next
st->top=newNode;
}
}
原文地址:https://www.cnblogs.com/miaobo/p/12435400.html