数据结构C#版笔记--堆栈(Stack)

 

堆栈(Stack)最明显的特征就是“先进后出”,本质上讲堆栈也是一种线性结构,符合线性结构的基本特点:即每个节点有且只有一个前驱节点和一个后续节点。

相对前面学习过的顺序表链表不同的地方在于:Stack把所有操作限制在"只能在线性结构的某一端"进行,而不能在中间插入或删除元素。下面是示意图:

从示意图中可以看出,堆栈有二种实现方式:基于数组的顺序堆栈实现、类似链表的链式堆栈实现

先抽象堆栈的接口IStack:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace 栈与队列
{
    public interface IStack<T>
    {
        /// <summary>
        /// 返回堆栈的实际元素个数
        /// </summary>
        /// <returns></returns>
        int Count();
 
        /// <summary>
        /// 判断堆栈是否为空
        /// </summary>
        /// <returns></returns>
        bool IsEmpty();
 
        /// <summary>
        /// 清空堆栈里的元素
        /// </summary>
        void Clear();
 
        /// <summary>
        /// 入栈:将元素压入堆栈中
        /// </summary>
        /// <param name="item"></param>
        void Push(T item);
 
        /// <summary>
        /// 出栈:从堆栈顶取一个元素,并从堆栈中删除
        /// </summary>
        /// <returns></returns>
        T Pop();
 
        /// <summary>
        /// 取堆栈顶部的元素(但不删除)
        /// </summary>
        /// <returns></returns>
        T Peek();
    }
}

顺序堆栈(SeqStack)的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Text;
 
namespace 栈与队列
{
    public class SeqStack<T>:IStack<T>
    {
        private int maxsize;
        private T[] data;
        private int top;       
 
 
        public SeqStack(int size)
        {
            data = new T[size];
            maxsize = size;
            top = -1;
        }
 
        #region //接口实现部分
        public int Count()
        {
            return top + 1;
        }
 
        public void Clear()
        {
            top = -1;
        }
 
        public bool IsEmpty()
        {
            return top == -1;
        }
 
        public void Push(T item)
        {
            if (IsFull())
            {
                Console.WriteLine("Stack is full");
                return;
            }
            data[++top] = item;
        }
 
 
        public T Pop()
        {
            T tmp = default(T);
            if (IsEmpty())
            {
                Console.WriteLine("Stack is empty");
                return tmp;
            }
            tmp = data[top];
            top--;
            return tmp;
        }
 
        public T Peek()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Stack is empty!");
                return default(T);
            }
            return data[top];
        }
        #endregion
 
        public bool IsFull()
        {
            return top == maxsize - 1;
        }
 
 
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = top;i>=0;i--)
            {
                sb.Append(data[i] + ",");
            }
            return sb.ToString().Trim(',');
        }       
 
    }
}

链式堆栈(LinkStack)的实现

先定义节点Node.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace 栈与队列
{
    public class Node<T>
    {
        private T data;
 
        private Node<T> next;
 
        public Node(T data, Node<T> next)
        {
            this.data = data;
            this.next = next;
        }
 
        public Node(Node<T> next)
        {
            this.next = next;
            this.data = default(T);
             
        }
 
        public Node(T data)
        {
            this.data = data;
            this.next = null;
        }
 
        public Node()
        {
            this.data = default(T);
            this.next = null;
        }
 
        public T Data {
            get { return this.data; }
            set { this.data = value; }
        }
 
        public Node<T> Next
        {
            get { return next; }
            set { next = value; }
        }
    }
}

下面是LinkStack.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Text;
 
namespace 栈与队列
{
    public class LinkStack<T>:IStack<T>
    {
 
        private Node<T> top;
        private int num;//节点个数
     
        /// <summary>
        /// 顶部节点
        /// </summary>
        public Node<T> Top
        {
            get { return top; }
            set { top = value; }
        }
        
 
        public LinkStack()
        {
            top = null;
            num = 0;
        }
 
        public int Count()
        {
            return num;
        }
 
        public void Clear()
        {
            top = null;
            num = 0;
        }
 
        public bool IsEmpty()
        {
            if (top == null && num == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 
        public void Push(T item)
        {
            Node<T> q = new Node<T>(item);
            if (top == null)
            {
                top = q;
            }
            else
            {
                q.Next = top;
                top = q;
            }
            num++;
        }
 
        public T Pop()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Stack is empty!");
                return default(T);
            }
            Node<T> p = top;
            top = top.Next;
            num--;
 
            return p.Data;
        }
 
        public T Peek()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Stack is empty!");
                return default(T);
            }
            return top.Data;
        }
 
 
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            if (top != null)
            {
                sb.Append(top.Data.ToString() + ",");
                Node<T> p = top;
                while (p.Next != null)
                {                   
                    sb.Append(p.Next.Data.ToString()+ ",");
                    p = p.Next;
                }
            }
 
            return sb.ToString();
        }
    }
}

测试代码片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Console.WriteLine("顺序堆栈测试开始...");
SeqStack<int> seqStack = new SeqStack<int>(10);
seqStack.Push(1);
seqStack.Push(2);
seqStack.Push(3);
 
Console.WriteLine(seqStack);
Console.WriteLine(seqStack.Peek());
Console.WriteLine(seqStack);
Console.WriteLine(seqStack.Pop());
Console.WriteLine(seqStack);
 
Console.WriteLine("链堆栈测试开始...");
LinkStack<int> linkStack = new LinkStack<int>();
linkStack.Push(1);
linkStack.Push(2);
linkStack.Push(3);
 
Console.WriteLine(linkStack);
Console.WriteLine(linkStack.Peek());
Console.WriteLine(linkStack);
Console.WriteLine(linkStack.Pop());
Console.WriteLine(linkStack);
 
Console.ReadLine();

.Net中System.Collections.Generic.Stack<T>已经提供了堆栈的基本实现,明白原理后,仍然推荐大家使用内置的实现。

作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转:stack的更多相关文章

  1. 线性数据结构之栈——Stack

    Linear data structures linear structures can be thought of as having two ends, whose items are order ...

  2. Java 堆内存与栈内存异同(Java Heap Memory vs Stack Memory Difference)

    --reference Java Heap Memory vs Stack Memory Difference 在数据结构中,堆和栈可以说是两种最基础的数据结构,而Java中的栈内存空间和堆内存空间有 ...

  3. [数据结构]——链表(list)、队列(queue)和栈(stack)

    在前面几篇博文中曾经提到链表(list).队列(queue)和(stack),为了更加系统化,这里统一介绍着三种数据结构及相应实现. 1)链表 首先回想一下基本的数据类型,当需要存储多个相同类型的数据 ...

  4. Stack Overflow 排错翻译 - Closing AlertDialog.Builder in Android -Android环境中关闭AlertDialog.Builder

    Stack Overflow 排错翻译  - Closing AlertDialog.Builder in Android -Android环境中关闭AlertDialog.Builder 转自:ht ...

  5. Uncaught RangeError: Maximum call stack size exceeded 调试日记

    异常处理汇总-前端系列 http://www.cnblogs.com/dunitian/p/4523015.html 开发道路上不是解决问题最重要,而是解决问题的过程,这个过程我们称之为~~~调试 记 ...

  6. Stack操作,栈的操作。

    栈是先进后出,后进先出的操作. 有点类似浏览器返回上一页的操作, public class Stack<E>extends Vector<E> 是vector的子类. 常用方法 ...

  7. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  8. [LeetCode] Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  9. Stack的三种含义

    作者: 阮一峰 日期: 2013年11月29日 学习编程的时候,经常会看到stack这个词,它的中文名字叫做"栈". 理解这个概念,对于理解程序的运行至关重要.容易混淆的是,这个词 ...

  10. Uncaught RangeError: Maximum call stack size exceeded 超出最大调用值(个人解释)

    写了段jq后,报这个错,度娘未解,灵光一闪,找到原因,上代码: Html 结构: <a href="javascript:;" class="item-pic&qu ...

随机推荐

  1. Git 的4个阶段的撤销更改

    虽然git诞生距今已有12年之久,网上各种关于git的介绍文章数不胜数,但是依然有很多人(包括我自己在内)对于它的功能不能完全掌握.以下的介绍只是基于我个人对于git的理解,并且可能生编硬造了一些不完 ...

  2. bigdata-02-hadoop2.8.4-resourceHA安装

    1, 电脑环境准备 1), 关闭selinux vim /etc/selinux/config SELINUX=disabled 2), 时间同步 yum -y install chrony 修改时间 ...

  3. 编译centos6.5:glibc 升级2.14问题

    第一种:不需要 ln 创建软连接,缺点嘛,就是直接安装到系统文件夹/lib64下,想换回来就比较麻烦.(我选择的第二种,因为公司需要fpm打包,写到脚本里面,第一种之间安装在/usr目录下,打包的包安 ...

  4. linux之后台运行程序 nohup和& 的区别

    1.nohup 用途:不挂断地运行命令,即使终端ssh关闭了也一直运行. 语法:nohup Command [ Arg … ] [ & ] 例:nohup start.sh & 无论是 ...

  5. java.util.ServiceLoader的用法

    在很多开源组件里经常会看到java.util.ServiceLoader的使用,这里给大家介绍下怎么通过ServiceLoader找到一个接口的所有实现类. 我们新建一个接口Hello public ...

  6. es简单介绍及使用注意事项

    是什么? Elasticsearch是一个基于Apache Lucene(TM)的开源搜索引擎.无论在开源还是专有领域,Lucene可以被认为是迄今为止最先进.性能最好的.功能最全的搜索引擎库. El ...

  7. 【IT笔试面试题整理】字符串转数组+数组转字符串

    [试题描述]定义一个函数,字符串转数组数组转字符串 [参考代码] public static int strToInt(String str) { int i = 0, num = 0; char[] ...

  8. KMP算法理解(转)

    (作者matrix67) KMP算法是拿来处理字符串匹配的.换句话说,给你两个字符串,你需要回答,B串是否是A串的子串(A串是否包含B串).比如,字符串A="I'm matrix67&quo ...

  9. Spring 环境与profile(二)——Properties with Spring

    1. 简述 Spring profile用例,分3个场景(Test, Dev, Prod)相对Spring 环境与profile(一)——超简用例多了根据具体的profile获取对应的Properti ...

  10. 在jQuery定义自己的扩展方法函数

    今早复习昨天的练习jQuery的DropDownList联动功能,如果想看回<jQuery实现DropDownList(MVC)>http://www.cnblogs.com/insus/ ...