常见的数据结构
栈(stack)
- 栈是一个先入后出(FILO-First In Last Out)的有序列表
- 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
- 出栈(pop)和入栈(push):
栈(Stack)是一个后进先出(Last in first out,LIFO)的线性表,它要求只在表尾进行删除和插入操作
public interface IStack<E> {
//1.判断空栈
public boolean isEmpty();
//2.判断栈满
public boolean isMax();
//3.入栈
public boolean push(E e);
//4.出栈
public E pop();
//5.返回栈顶
public E peek();
//6.返回元素在栈中的位置
public int getIndex(E e);
//7.返回栈的实际长度
public int size();
//8.返回栈容量
public int getStackSize();
//9.打印栈
public void display();
}
队列
- 定义
只能在表的一端(队尾)进行插入,在另一端(队头)进行删除运算的线性表 - 逻辑结构
与线性表相同,仍为一对一关系 - 存储结构
用顺序队列或链队存储均可 - 运算规则
先进先出(FIFO) - 实现方式
关键是编写入队和出队函数,具体实现依顺序队或链队的不同而不同
- 循环顺序队列:
//队列接口
public interface Queue {
//入队
public void append(Object obj) throws Exception;
//出队
public Object delete() throws Exception;
//获得队头元素
public Object getFront() throws Exception;
//判断对列是否为空
public boolean isEmpty();
}
链表
- 链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)。
单向链表(Single-Linked List)
- 单链表是链表中结构最简单的。一个单链表的节点(Node)分为两个部分,第一个部分(data)保存或者显示关于节点的信息,另一个部分存储下一个节点的地址。最后一个节点存储地址的部分指向空值。
public class SingleLinkedList {
private int size;//链表节点的个数
private Node head;//头节点
public SingleLinkedList(){
size = 0;
head = null;
}
//链表的每个节点类
private class Node{
private Object data;//每个节点的数据
private Node next;//每个节点指向下一个节点的连接
public Node(Object data){
this.data = data;
}
}
//在链表头添加元素 [D->C->B->A]
public Object addHead(Object obj){
Node newHead = new Node(obj);
if(size == 0){
head = newHead;
}else{
newHead.next = head;
head = newHead;
}
size++;
return obj;
}
//在链表头删除元素
public Object deleteHead(){
Object obj = head.data;
head = head.next;
size--;
return obj;
}
//查找指定元素,找到了返回节点Node,找不到返回null
public Node find(Object obj){
Node current = head;
int tempSize = size;
while(tempSize > 0){
if(obj.equals(current.data)){
return current;
}else{
current = current.next;
}
tempSize--;
}
return null;
}
//删除指定的元素,删除成功返回true
public boolean delete(Object value){
if(size == 0){
return false;
}
Node current = head;
Node previous = head;
while(current.data != value){
if(current.next == null){
return false;
}else{
previous = current;
current = current.next;
}
}
//如果删除的节点是第一个节点
if(current == head){
head = current.next;
size--;
}else{//删除的节点不是第一个节点
previous.next = current.next;
size--;
}
return true;
}
//判断链表是否为空
public boolean isEmpty(){
return (size == 0);
}
//显示节点信息
public void display(){
if(size >0){
Node node = head;
int tempSize = size;
if(tempSize == 1){//当前链表只有一个节点
System.out.println("["+node.data+"]");
return;
}
while(tempSize>0){
if(node.equals(head)){
System.out.print("["+node.data+"->");
}else if(node.next == null){
System.out.print(node.data+"]");
}else{
System.out.print(node.data+"->");
}
node = node.next;
tempSize--;
}
System.out.println();
}else{//如果链表一个节点都没有,直接打印[]
System.out.println("[]");
}
}
}