Algorithm——简单数据结构之队列和链表
队列是一种先进先出策略,而链表中的各元素按线性顺序排列。数组的线性顺序是由数组的下标决定的,但链表的顺序是由各个对象里的指针决定的。队列有入队和出队操作,链表则有插入、删除、查询表中节点的操作。
队列和双向链表的一种简单Java实现代码如下:
/**
*
* 队列是一种先进先出策略,有入队和出队操作
*
* 通过数组实现的简单队列
*
* @author coder
*
*/
class Queue {
private int head = 0;// 对头位置
private int tail = 0;// 下一个元素插入的位置
private int queue[];
public Queue() {
queue = new int[256];
}
/*
* 入队操作
*/
public void enQueue(int x) {
if (tail >= queue.length)
throw new IllegalArgumentException("queue overflaw with value: " + x);
queue[tail] = x;
tail++;
}
/*
* 出队操作
*/
public int deQueue() {
if (head >= tail)
throw new IllegalAccessError("Queue is empty, can't dequeue");
int headV = queue[head];
head++;
return headV;
}
}
/**
* 链表可以是单链接的,此时省去每个元素中的prev指针; 链表可以是已排序的,它的顺序与每个节点中关键字的线性顺序一致;
* 链表可以是未排序的,元素可以以任何顺序出现; 同时,链表也可以是循环的,表头元素的prev指针指向表尾元素,表尾元素的next指针指向表头元素
*
* @author coder
*
* 一个简单双向链表的实现
*/
class DoubleLinkedList {
/**
* 链表的节点
*
* @author coder
*
*/
class Node {
int key;// 关键字
Node prev;// 指向前一个节点对象
Node next;// 指向下一个节点对象
Node() {
key = 0;
prev = new Node();
next = new Node();
}
}
private Node head = null;// 链表的首节点
/**
* 插入节点x到链表的前端
*
* @param key
*/
public void listInsert(Node x) {
x.next = head;
if (head != null)
head.prev = x;
head = x;
x.prev = null;
}
/**
* 搜索值为key的节点
*
* @param key
* @return
*/
public Node listSearch(int key) {
Node x = head;
while (x != null && x.key != key)
x = x.next;
return x;
}
/**
* 删除节点x
*
* @param key
* @return
*/
public void listDelete(Node x) {
if (x.prev != null)
x.prev.next = x.next;
else
head = x.next;
if (x.next != null)
x.next.prev = x.prev;
}
}