zoukankan      html  css  js  c++  java
  • 带头结点和不带头结点的链栈基本操作


    C++数据结构
    把链栈想象成单链表头结点的后插和后删操作

    不带头结点的链栈

    //不带头结点的链栈
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    using namespace std;
    
    typedef struct Linknode1 {
    	int data;
    	struct Linknode1* next;
    }*LiStack1;
    
    void InitStack1(LiStack1& L) {
    	L= NULL;
    }
    
    //进栈
    LiStack1 Push1(LiStack1& L, int x) {
    	Linknode1* s = (LiStack1)malloc(sizeof(Linknode1));
    	s->data = x;
    	s->next = L;
    	L= s;
    	return L;
    }
    //出栈
    bool Pop1(LiStack1 & L) {
    	if (L == NULL) {
    		return false;
    	}
    	L = L->next;
    	printf("-------------------------");
    	return true;
    }
    
    //读栈
    void Gettop1(LiStack1 L) {
    	while (L) {
    		
    		printf("%d", L->data);
    		
    		L = L->next;
    	}
    	printf("
    ");
    }
    int main()
    {
    	LiStack1 L;
    	InitStack1(L);
    	L = Push1(L, 2);
    	L = Push1(L, 8);
    	L = Push1(L, 9);
    	L = Push1(L, 6);
    	L = Push1(L, 4);
    	Gettop1(L);
    	Pop1(L);
    	Pop1(L);
    	Pop1(L);
    	Gettop1(L);
    	return 0;
    }
    

    结果:
    在这里插入图片描述

    带头结点的链栈

    //带头结点的链栈
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    using namespace std;
    //带头结点
    typedef struct Linknode {
    	int data;
    	struct Linknode* next;
    }*LiStack;
    
    bool InitStack(LiStack &L) {
    	L = (LiStack)malloc(sizeof(Linknode));
    	if (L == NULL) {
    		return false;
    	}
    	L->next=NULL;
    	return true;
    }
    
    //进栈
    LiStack Push(LiStack &L, int x) {
    	Linknode *s = (LiStack)malloc(sizeof(Linknode));
    	s->data = x;
    	s->next = L->next;
    	L->next = s;
    	return L;
    }
    //出栈
    bool Pop(LiStack& L) {
    	if (L->next == NULL) {
    		return false;
    	}
    	Linknode *q=L->next;
    	L->next= q->next;
    	printf("-------------------------");
    	return true;
    }
    
    //读栈
    void Gettop(LiStack L) {
    	while (L->next) {
    		L = L->next;
    		printf("%d", L->data);
    	}
    	printf("
    ");
    }
    int main()
    {
    	LiStack L;
    	InitStack(L);
    	L=Push(L, 2);
    	L = Push(L, 8);
    	L = Push(L, 9);
    	L = Push(L, 6);
    	L = Push(L, 4);
    	Gettop(L);
    	Pop(L);
    	Pop(L);
    	Pop(L);
    	Gettop(L);
    	return 0;
    }
    

    结果:
    在这里插入图片描述

  • 相关阅读:
    sockjs-node/info 请求错误
    vue项目中 —— rem布局适配方案
    JS判断对象是否为空
    JS生成一个特定格式随机数
    vue项目中axios请求网络接口封装
    vue报错——error Unexpected console statement no-console
    vue切换页面修改网页的标题
    处理js两个数相乘的坑
    js科学计数法问题
    (9)kendo UI使用基础介绍与问题整理——Validator/基础说明、实例介绍
  • 原文地址:https://www.cnblogs.com/Sawye-sxy/p/13933333.html
Copyright © 2011-2022 走看看