0
点赞
收藏
分享

微信扫一扫

自定义实现栈(使用链表)

李雨喵 2022-04-05 阅读 34

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;

namespace DataStructure
{
    class Nodes//链表节点类
    {
        public int data;
        public Nodes next;

        public Nodes(int data)
        {
            this.data = data;
            this.next = null;
        }
    }

    class NodeStack//链表结构类
    {
        public Nodes head;
        public Nodes tail;

        public bool isEmpty()
        {
            return head == null;
        }

        public void printStack()
        {
            Nodes tmp = head;
            while (tmp != null)
            {
                Write("["+tmp.data+"]");
                tmp = tmp.next;
            }
            WriteLine();
        }

        public void insertNode(int data)
        {
            Nodes tmp = new Nodes(data);
            if (isEmpty())
            {
                this.head = tmp;
                this.tail = tmp;
            }
            else
            {
                this.tail.next = tmp;
                this.tail = tmp;
            }
            
        }

        public void popNode()
        {
            if (this.isEmpty())//空栈
            {
                WriteLine("当前栈元素空");
                return;
            }
            Nodes tmp = this.head;
            if (tmp == tail)//仅仅一个元素情况
            {
                this.head = null;
                this.tail = null;
            }
            else
            {
                
                while (tmp.next != tail)
                {
                    tmp = tmp.next;
                }
                tmp.next = tail.next;
                tail = tmp;
            }
        }
    }


    class stackProgran//启动测试类
    {
        public static void startStackNode()
        {
            NodeStack nodeStack = new NodeStack();
            int choice;
            while (true)
            {
                Write("(0)结束,(1)将数据压入堆栈,(2)数据弹出堆栈:");
                string str = ReadLine();
                choice = int.Parse(str);
                if (choice == 0)
                {
                    break;
                }else if(choice == 1){
                    WriteLine("\n请输入数字:");
                    int tmp = int.Parse(ReadLine());
                    nodeStack.insertNode(tmp);
                    WriteLine("加入数据后的堆栈内容:");
                    nodeStack.printStack();
                }else if (choice == 2)
                {
                    nodeStack.popNode();
                    WriteLine("\n弹栈后的堆栈内容:");
                    nodeStack.printStack();
                }
            }
        }
    }
}

举报

相关推荐

0 条评论