隊(duì)列(JAVA實(shí)現(xiàn))“>數(shù)據(jù)結(jié)構(gòu)->隊(duì)列(JAVA實(shí)現(xiàn))
隊(duì)列的操作
隊(duì)列的操作一般包括:進(jìn)隊(duì)列、出隊(duì)列,訪問隊(duì)列頭元素、刪除隊(duì)列頭元素、判斷隊(duì)列是否為空、獲得隊(duì)列大小這些核心操作。
隊(duì)列的順序?qū)崿F(xiàn)
和棧結(jié)構(gòu)一樣隊(duì)列也有兩種實(shí)現(xiàn)方式相對(duì)于順序?qū)崿F(xiàn)方式,鏈?zhǔn)綄?shí)現(xiàn)相對(duì)比較簡(jiǎn)單,只需要利用Node結(jié)構(gòu),記錄下隊(duì)列的頭Node和尾巴Node,在記錄下元素個(gè)數(shù)就可以了。實(shí)現(xiàn)代碼如下:
package dateStructer.queue;
public class MyQueue implements Queue {
/**
* 雙向鏈表結(jié)構(gòu)
*/
public class LinkNode {
// 真正的數(shù)據(jù)域
private E date;
// 記錄上一個(gè)節(jié)點(diǎn)
private LinkNode prevLinkNode;
// 記錄下一個(gè)節(jié)點(diǎn)
private LinkNode nextLinkNode;
public LinkNode() {
}
public LinkNode(E date, LinkNode prevLinkNode, LinkNode nextLinkNode) {
this.date = date;
this.prevLinkNode = prevLinkNode;
this.nextLinkNode = nextLinkNode;
}
}
// 結(jié)點(diǎn)個(gè)數(shù)
private int nodeSize;
// 頭結(jié)點(diǎn)
private LinkNode headNode;
// 尾巴節(jié)點(diǎn)
private LinkNode tailNode;
public MyQueue(){
headNode = null;
tailNode = null;
}
/**
* 添加元素
*/
@Override
public boolean add(E element) {
if (nodeSize == 0) {
headNode = new LinkNode(element, null, tailNode);
}else {
if (tailNode == null) {
tailNode = new LinkNode(element, headNode, null);
headNode.nextLinkNode = tailNode;
nodeSize++;
return true;
}
LinkNode linkNode = tailNode;
tailNode = new LinkNode(element, linkNode, null);
linkNode.nextLinkNode = tailNode;
}
nodeSize++;
return true;
}
/**
* 訪問隊(duì)列頭元素
*/
@Override
public E element() {
return headNode.date;
}
/**
* 返回頭元素,不刪除頭元素
*/
@Override
public E peek() {
return headNode.date;
}
/**
* 返回頭元素,刪除頭元素
*/
@Override
public E poll() {
LinkNode headNodeTemp = headNode;
E date = headNodeTemp.date;
if(headNode.nextLinkNode == null){
headNode.date = null;
headNode = null;
nodeSize--;
return date;
}else{
headNode = headNode.nextLinkNode;
if(headNode == tailNode){
tailNode = null;
}
}
nodeSize--;
return headNodeTemp.date;
}
/**
* 清除所有元素
*/
@Override
public void clear() {
LinkNode linkNodeNowTemp = headNode;
for (int i = 0; i < nodeSize; i++) {
if (linkNodeNowTemp != tailNode && linkNodeNowTemp != headNode) {
linkNodeNowTemp = linkNodeNowTemp.nextLinkNode;
linkNodeNowTemp.prevLinkNode.nextLinkNode = null;
linkNodeNowTemp.prevLinkNode.prevLinkNode = null;
linkNodeNowTemp.prevLinkNode.date = null;
linkNodeNowTemp.prevLinkNode = null;
} else if (linkNodeNowTemp == tailNode) {
linkNodeNowTemp.prevLinkNode = null;
} else if (linkNodeNowTemp == headNode) {
linkNodeNowTemp.nextLinkNode = null;
}
}
headNode = null;
tailNode = null;
nodeSize = 0;
}
評(píng)論