1. 概念
1.1 栈的特征
栈和队列是访问受限的线性表。
1.2 栈的操作
push:入栈
pop:出栈
peek:显示栈顶
empty:判断栈是否为空
Java、python中的栈
java中有stack,python中数组可以直接当栈用。
JAVA:
public class MainTest {
public static void main(string[] args){
Stack<Integer> stack = new Stack();
stack.push(1);//入栈
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("栈顶元素为:"+stackpeek());
while (!stack.empty()){
//只显示一次栈顶
System.out.println("栈顶元素为:"+stackpeek());
//出栈且显示
System.out.println(stack.pop());
}
}
}
python
stack=[]
stack.append(1)
stack.append(2)
stack.append(3)
print(" 栈顶元素"+str(stack[-1]))
while stack:
print(stack[-1])
print(stack.pop())#出栈并显示
基于数组实现栈
思路
class Stack(object);
def __init__(self):
#初始化
self.items = []
def is_empty(self):
#判断是否为空
return self.items == []
def push(self,item):
#加入元素
self.items.append(item)
def pop(self):
#弹出元素
return self.items.pop()
def peek(self):
#返回栈顶元素
return self.items[len(self.items)-1]
def size(self);
#返回栈大小
return len(self.items)
#测试
stack = Stack()
stack.push(1)
stack.push(2)
print(stack.peek())
print(stack.pop())
基于链表实现栈
python不太合适,所以用C
C:
struct Node{
int data;
struct Node* next;
};//定义单一的一个链表节点
struct Stack{
struct Node* top;
};//定义栈顶
viod push(Stack* stack,int data){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=stack->top;//替换栈顶,相当于新的节点变成了头节点
stack->top =newNode;
}
int pop(struct Stack* stack){
if(stack->top==NULL){
print("栈已经空啦\n");
return -1;
};
int data = stack->top->data;//取出栈顶值,用于显示
struct Node* temp = stack ->top;//取出栈顶的地址,用于后面释放内存
stack->top = stack ->top->next;//栈顶的位置交给下面一个节点
free(temp);
return data;
}
int peek(struct Stack* stack){
if(stack->top==NULL){
print("栈已经空啦\n");
return -1;
};
return stack->top->data;
}
int empty(struct Stack* stack){
if(stack->top==NULL){
print("栈已经空啦\n");
return -1;
};
}