stack的java实现


import java.lang.Exception;

class MyStack
{
private static final int MAX_SIZE = 5;
private int[] t = new int[MAX_SIZE];
private int top = -1;

public void push(int x) throws Exception{

if(isFull()){
throw new Exception("栈已满");
}else{
t[++top] = x;
}

}

public int pop() throws Exception{

if(isEmpty()){
throw new Exception("栈为空");
}else{
return t[top--];
}
}

public boolean isFull(){
return top == MAX_SIZE - 1;
}

public boolean isEmpty(){
return top == -1;
}

public void printStack(){
for(int i = 0; i <= top; i++){
System.out.print(t[i]);
}
}
}

public class Temp
{
public static void main(String[] args) throws Exception{
MyStack ms = new MyStack();
ms.push(1);
ms.push(2);
ms.push(3);
ms.push(4);
ms.push(5);
System.out.println(ms.pop());
//ms.push(6);
ms.printStack();
}
}

顺序栈


class Node
{
public int data;
public Node next;

public Node(int data){
this.data = data;
}
}

class LinkedStack
{
private Node head;

public void push(int a){
Node node = new Node(a);
if(head == null){
head = node;
}else{
node.next = head;
head = node;
}
}

public int pop() throws Exception{
if(isEmpty()){
throw new Exception("栈为空");
}else{
Node temp = head;
head = head.next;
return temp.data;
}

}

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

public class TestLinkedStack
{
public static void main(String[] args) throws Exception{
LinkedStack ls = new LinkedStack();
ls.push(3);
ls.push(4);
System.out.println(ls.pop());
System.out.println(ls.pop());
//System.out.println(ls.pop());
}
}

链栈
DFS(深度优先搜索)是一种图遍历算法,可以用来解决很多问题,比如查找图中的连通分量、查找图中的路径等。在Java中,我们可以用Stack实现DFS算法。 DFS使用栈(Stack)数据结构来存储待遍历的节点。具体实现步骤如下: 1. 首先,我们需要创建一个Stack对象来存储待遍历的节点。 2. 然后,我们选择一个起始节点作为DFS的起点,将其入栈。 3. 接着,我们进行循环操作,直到栈为空为止。每次循环中,我们从栈中取出一个节点,将其标记为已访问,并遍历其邻居节点。将邻居节点中未访问过的节点入栈。 4. 最后,当栈为空时,表示DFS遍历结束。 这样就可以使用Stack实现DFS算法。下面是一个简单的Java代码示例: ```java import java.util.Stack; public class DFSStack { public void dfs(int[][] graph, int start) { boolean[] visited = new boolean[graph.length]; Stack<Integer> stack = new Stack<>(); stack.push(start); while (!stack.isEmpty()) { int node = stack.pop(); if (!visited[node]) { visited[node] = true; System.out.print(node + " "); for (int i = 0; i < graph.length; i++) { if (graph[node][i] == 1 && !visited[i]) { stack.push(i); } } } } } public static void main(String[] args) { int[][] graph = { {0, 1, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {0, 1, 1, 0, 1}, {0, 0, 1, 1, 0} }; DFSStack dfs = new DFSStack(); dfs.dfs(graph, 0); } } ``` 以上就是用Stack实现DFS算法的一个简单例子。通过这种方式,我们可以使用Stack数据结构来实现深度优先搜索算法,解决各种与图相关的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值