您的位置:首页 > 理论基础 > 数据结构算法

Java 数据结构和算法 栈和队列

2017-04-29 11:55 351 查看

栈是一种抽象的数据结构,栈只允许访问一个数据项,即最后插入的数据项,移除这个数据项之后才能访问倒数第二个数据,后进先出的原则。

class StackX
{
private int maxSize;        // 栈的大小
private long[] stackArray;
private int top;            // 栈顶
//--------------------------------------------------------------
public StackX(int s)
{
maxSize = s;             // 设置栈的大小
stackArray = new long[maxSize];  // 创建一个数组
top = -1;                // 没有元素的时候  置为-1
}
//--------------------------------------------------------------
public void push(long j)    // 加入元素
{
stackArray[++top] = j;
}
//--------------------------------------------------------------
public long pop()           // 取出栈顶元素
{
return stackArray[top--];
}
//--------------------------------------------------------------
public long peek()
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty()    // 判断栈是否为空
{
return (top == -1);
}
//--------------------------------------------------------------
public boolean isFull()     // 判断栈是否已满
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
}

public class StackApp
{
public static void main(String[] args)
{
StackX theStack = new StackX(10);  //创建一个栈
theStack.push(20);               // 装入元素
theStack.push(40);
theStack.push(60);
theStack.push(80);

while( !theStack.isEmpty() )
{
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}  // end while
System.out.println("");
}
}


栈的应用实例

单词逆序:

输入一个单词,输出字母顺序倒置后的词。

import java.io.*;
import java.util.Scanner;

class StackX {
private int maxSize;
private char[] stackArray;
private int top;

public StackX(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}

public void push(char j) {
stackArray[++top] = j;
}

public char pop() {
return stackArray[top--];
}

public char peek() {
return stackArray[top];
}

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

public  class ReverseApp {
public static void main(String[] args) {
System.out.println(doRev(getString()));
}

public static String getString() {
Scanner scan = new Scanner(System.in);
return scan.nextLine();
}

public static String doRev(String str) {
StackX theStack = new StackX(str.length());

for (int j = 0; j < str.length(); j++) {
char ch = str.charAt(j); // get a char from input
theStack.push(ch); // push it
}

String result = "";
while (!theStack.isEmpty()) {
char ch = theStack.pop();
result += String.valueOf(ch);
}
return result;
}

}


应用:匹配括号

栈常用来解析某种类型的文本串,比如解析一串字符中括号是否匹配,{ } () [ ] ,基本方法就是 遇见左括号时压入栈,遇见右括号时取出栈顶元素检查是否匹配,以此类推,如果所有匹配,则匹配成功,否则匹配失败。

import java.util.Scanner;

class StackX {
private int maxSize;
private char[] stackArray;
private int top;

public StackX(int s) {
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}

public void push(char j)
{
stackArray[++top] = j;
}

public char pop() //取出栈顶元素
{
return stackArray[top--];
}

public char peek() //得到栈顶元素   栈并没有改变
{
return stackArray[top];
}

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

public class BracketsApp {
public static void main(String[] args) {
check(getString());

}

public static String getString() {
Scanner scan = new Scanner(System.in);
return scan.nextLine();
}

public static void check(String str) {
int stackSize = str.length();
StackX theStack = new StackX(stackSize);

for (int j = 0; j < str.length(); j++)
{
char ch = str.charAt(j);
switch (ch) {
case '{':
case '[':
case '(':
theStack.push(ch);
break;

case '}':
case ']':
case ')':
if (!theStack.isEmpty())
{
char chx = theStack.pop();
if ((ch == '}' && chx != '{') || (ch == ']' && chx != '[') || (ch == ')' && chx != '('))
System.out.println("Error: " + ch + " at " + j);
} else
System.out.println("Error: " + ch + " at " + j);
break;
default:
break;
}
}

if (!theStack.isEmpty())
System.out.println("匹配失败");
}
}




队列

队列也是一种数据结构,有点类似栈,但是在队列中类似于排队,先来的先服务,也可以想象成管道,即先进先出。

代码展示:

class Queue {
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;

public Queue(int s) {
maxSize = s;
queArray = new long[maxSize];
front = 0;// 队头标志
rear = -1;// 队尾标志
nItems = 0;// 队列中元素个数
}

public void insert(long j) {
if (rear == maxSize - 1)
rear = -1;
queArray[++rear] = j;
nItems++;
}

public long remove() {
long temp = queArray[front++];
if (front == maxSize)
front = 0;
nItems--;
return temp;
}

public long peekFront() {
return queArray[front];
}

public boolean isEmpty() {
return (nItems == 0);
}

public boolean isFull() {
return (nItems == maxSize);
}

public int size() {
return nItems;
}

}

public class QueueApp {
public static void main(String[] args) {
Queue theQueue = new Queue(5);

theQueue.insert(10);
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);

theQueue.remove();
theQueue.remove();
theQueue.remove();

theQueue.insert(50);
theQueue.insert(60);
theQueue.insert(70);
theQueue.insert(80);

while (!theQueue.isEmpty()) {
long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");
}
System.out.println("");
}
}


双端队列

双端队列就是两端都是结尾的队列,队列的每一端都可以插入或者移除数据

优先级队列

优先级队列是比栈和队列更专用的数据结构,像普通队列一样,它也有一个一个对头和一个队尾,并且也是从队头移除数据项,不过在优先级队列中,数据按关键字的值有序,数据插入的时候会按照顺序插入到合适的位置以保证队列有序。

class PriorityQ {
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int nItems;

public PriorityQ(int s) {
maxSize = s;
queArray = new long[maxSize];
nItems = 0;
}

public void insert(long item) {
int j;

if (nItems == 0)
queArray[nItems++] = item; // 队列为空 直接插入
else {// 否则要排序
for (j = nItems - 1; j >= 0; j--) {
if (item > queArray[j])
queArray[j + 1] = queArray[j];
else
break;
}
queArray[j + 1] = item;
nItems++;
}
}

public long remove() {
return queArray[--nItems];
}

public long peekMin() {
return queArray[nItems - 1];
}

public boolean isEmpty() {
return (nItems == 0);
}

public boolean isFull() {
return (nItems == maxSize);
}

}

public class PriorityQApp {
public static void main(String[] args) {
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);

while (!thePQ.isEmpty()) {
long item = thePQ.remove();
System.out.print(item + " "); // 10, 20, 30, 40, 50
}
System.out.println("");
}
}


优先级队列与队列在代码实现上不同之处主要在于插入的时候要排序。

栈和队列暂时就写这么多,下一节实现栈和队列的综合应用。计算表达式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: