一:介绍栈

  1. 栈的英文(stack)
  2. 栈是一个先入先出(FILO-First In Last Out)的有序列表。
  3. 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一个端机械能一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(TOP),另一端为固定的一端,称为栈底(Bottom)
  4. 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除。

1574047858600

二:栈的引用场景

1574047995815

三:使用数组模拟栈

1574054079167

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
public class ArrayStack
{
private int maxsize;//声明栈的长度
private int top = -1;//栈顶
private int[] stack;
//构造器
public ArrayStack(int maxsize)
{
this.maxsize = maxsize;
stack = new int[maxsize];
}
//栈满
public bool isFull()
{
return top == maxsize - 1;
}
//栈空
public bool isEmpty()
{
return top == -1;
}
//入栈-push
public void push(int n)
{
if (isFull())
{
Console.WriteLine("栈满,无法添加!");
return;
}
top++;
stack[top] = n;
}
//出栈-pop
public int pop()
{
if (isEmpty())
{
throw new Exception("栈空,无法出栈!");
}
int value=stack[top];
top--;
return value;
}
//遍历栈
public void showlist()
{
if (isEmpty())
{
throw new Exception("栈空,无法出栈!");
}
for (int i = top; i >= 0; i--)
{
Console.WriteLine(pop());
}
}

四:使用链表模拟栈

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
public class LinkedStack
{
public Node head = new Node(-1);//虚拟头结点
//链空
public bool isEmpty()
{
return head.next == null;
}
//入栈
public void push(int n)
{
Node temp = new Node(n);
Node temp2 = head;
while (temp2.next != null)
{
temp2 = temp2.next;
}
temp2.next = temp;

}
//出栈
public int pop()
{
Node temp =head;
int value = 0;
if (temp.next == null)
{
temp.next = null;
}
else
{
value = temp.next.no;
temp.next = temp.next.next;
}
return value;
}
//展示列表
public void showlist()
{
Node temp = head;
if (isEmpty())
{
Console.WriteLine("栈空!");
}
while (temp.next!=null)
{
Console.WriteLine(pop());
temp = temp.next;
}
Console.WriteLine(temp.no);
}
}
public class Node
{
public int no;
public Node next;
public Node(int no)
{
this.no = no;
}
}