java数据结构之LinkedQueue(用链表实现的双端单向队列)

来源:互联网 发布:edius软件下载 mac 编辑:程序博客网 时间:2024/06/05 02:53
 

 

1.接口

package com.jimmy;

public interface QueueInterf<T> {

//入队列,放在队列后头

public void enqueue(T newEntry);

//出队列,从队列开头出

public T dequeue();

public T getFront();

public boolean isEmpty();

//删除队列中所有元素

public void clear();

}

2.链表实现的双端队列(单向,节点里没有pre)

 first;//前(端)哨兵节点,这里不同与MylinkedList的做法,并没有初始化first,last对象,仅仅把它当做引用,但仍然可以理解为哨兵,//有点像C的做法

 

last;//后(端)哨兵节点

 

//                   |----| |-----| |----|

// | first|-->   | 4 |  |  5   | |  3 | <--|last|      length=3

//                  |----| |---- -| |----|

 

 

package com.jimmy.impl;

 

import com.jimmy.Node;

 

import com.jimmy.QueueInterf;

 

import com.jimmy.ListInterface.MNode;

 

public class LinkedQueue<T>implements QueueInterf<T> {

/**

* @param args

*/

 

 

public class Node {

private Tdata;

private Nodenext;

public Node(T data, Node node) {

this.data = data;

next = node;

}

public T getData() {

returndata;

}

}

 

 

public Node<T>first;//前(端)哨兵节点,这里不同与MylinkedList的做法,并没有初始化first,last对象,仅仅把它当做引用,但仍然可以理解为哨兵

 

public Node<T>last;//后(端)哨兵节点

 

publicintlength;//有效数据长度

 

 

//                 |----| |-----| |----|

// | first|-->  | 4 | | 5   |  |  3 | <--|last| length=3

//                 |----| |-----| |----|

 

 

public LinkedQueue(){

first=null;//这里不同与MylinkedList的做法,并没有初始化first,last对象

 

last=null;

}

publicstaticvoid main(String[] args) {

LinkedQueue<Integer> q=new LinkedQueue<Integer>();

q.enqueue(4);

q.enqueue(5);

q.enqueue(3);

q.display();

q.dequeue();

q.dequeue();

q.display();

}

publicvoid enqueue(T newEntry) {

Node<T> newNode=new Node<T>(newEntry,null);

if(isEmpty())

{

first=newNode;// 仅仅把fist当做引用,所以直接赋值给first,即把newnode当做第一个first

 

last=newNode;

 

//                 |----|

// | first|--> | 4  | <--|last|

//                |----|

 

}else{

last.next=newNode;//有点像C的做法

last=newNode;

}

length++;

}

public T dequeue() {

T front=null;

if(!isEmpty())

{

front=first.getData();

first=first.next;

}

length--;

return front;

}

public T getFront() {

T front=null;

if(!isEmpty())

{

front=first.getData();

}

return front;

}

publicboolean isEmpty() {

returnfirst==null;

}

publicvoid clear() {

first=null;

last=null;

}

publicint getLength()

{

returnlength;

}

publicvoid display() {

Node<T> cur=first;//first为哨兵

while(cur!=null){//从一开始

//if(cur!=null)

System.out.print(cur.getData()+",");

cur=cur.next;

}

System.out.println();

}

}


 

原创粉丝点击