874
iPhone_iPad_Mac_apple
數據結構之棧與隊列
一。棧
1。概念:棧(stack)是一種線性數據結構,隻能訪問它的一端來存儲或者讀取數據。棧是一種後進先出的結構(LIFO)
2。棧的主要操作:
.clear()——清棧
.isEmpty()——檢查棧是否為空
.push(e)——壓棧
.pop()——出棧
.topEl()——返回棧頂元素
3。棧的java實現:使用數組鏈表實現

/** *//**
*
*/
package com.sohu.blog.denns_zane.stackqueue;


/** *//**
* @author dennis
*
*/

public abstract class AbstractStack
{
public abstract Object pop();

public abstract void push(Object obj);

public abstract Object topEl();

public abstract boolean isEmpty();

public abstract void clear();
}



/** *//**
*
*/
package com.sohu.blog.denns_zane.stackqueue;


/** *//**
* @author dennis
*
*/

public class Stack extends AbstractStack
{
private java.util.ArrayList pool = new java.util.ArrayList();


public Stack()
{
}


public Stack(int n)
{
pool.ensureCapacity(n);
}


public void clear()
{
pool.clear();
}


public boolean isEmpty()
{
return pool.isEmpty();
}


public Object topEl()
{
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.get(pool.size() - 1);
}


public Object pop()
{
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.remove(pool.size() - 1);
}


public void push(Object el)
{
pool.add(el);
}


public String toString()
{
return pool.toString();
}
}
4。棧的應用:
1)程序中的匹配分割符,如(,[,{等符號
2)大數的運算,比如大數相加,轉化為字符串,利用棧處理
3)回文字,例子:

/** *//**
*
*/
package com.sohu.blog.denns_zane.stackqueue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/** *//**
* @author dennis
*
*/

public class HuiWen
{


/** *//**
* @param args
*/

public static void main(String[] args)
{
BufferedReader buffer = new BufferedReader(new InputStreamReader(
System.in));

try
{
String str = buffer.readLine();
if (str != null)
isHuiWen(str);


} catch (IOException e)
{
e.printStackTrace();
}
// TODO Auto-generated method stub

}


public static void isHuiWen(String str)
{
int length = str.length();
char[] ch = str.toCharArray();
Stack stack = new Stack();

if (length % 2 == 0)
{

for (int i = 0; i < length / 2; i++)
{
stack.push(ch[i]);
}

for (int i = length / 2; i < length - 1; i++)
{

if (ch[i] != ((Character) stack.pop()).charValue())
{
System.out.println("不是回文字!!");
return;
}

}

System.out.println(str + "是回文字!!");

} else
{

for (int i = 0; i < length / 2; i++)
{
stack.push(ch[i]);
}

for (int i = (length / 2 + 1); i < length - 1; i++)
{

if (ch[i] != ((Character) stack.pop()).charValue())
{
System.out.println("不是回文字!!");
return;
}
}
System.out.println(str + "是回文字!!");
}

}

}
4)java虛擬機中的本地方法棧
二。隊列(queue)
1。概念:隊列也是線性結構,從尾部添加元素,從頭部刪除元素。與棧相反,隊列是先入先出結構(FIFO)
2。隊列主要操作:
.clear() ——清空隊列
.isEmpty()——判斷隊列是否為空
.enqueue(el)——從尾部插入元素el
.dequeue()——從隊列中起出第一個元素,並刪除
.firstEl()——返回隊列第一個元素,不刪除。
3。隊列的實現:
1)環形數組:需要考慮隊列已滿的兩種情況,1,第一個元素在最後一個元素之後;2,第一個元素在第一單元,最後一個元素在最後單元。給出一個java實現:
4。隊列的應用:線性規劃方麵
最後更新:2017-05-17 11:36:28