1. 基础-区分数组和链表
- 对数组和链表的优缺点
数据结构 |
优点 |
缺点 |
数组 |
通过索引可以直接访问任意元素 |
在初始化就需要知道元素的数量 |
链表 |
使用的空间大小和元素数量成正比 |
需要通过引用访问任意元素 |
- 对于常用的数据结构的举例
数据结构 |
抽象数据类型 |
数据表示 |
父链接树 |
UnionFind |
整形数组 |
二分查找树 |
BST |
含有两个链接的结点 |
字符串 |
String |
数组、偏移量和长度 |
散列表(拉链法) |
SeparateChainingHashST |
链表数组 |
散列表(线性探测法) |
LinearProbingHashST |
两个对象数组 |
图的邻接链表 |
Graph |
Bag对象的数组 |
单词查找树 |
TrieST |
含有链接数组的结点 |
三向单词查找树 |
TST |
含有三个链接的结点 |
1. 更常用的数据结构了
栈,链表,包
1. 栈
- 栈是后进先出 通常也是可说下压栈
- 在java中可以使用定义好的栈Stack,或者你自己可以实现适合自己的问题的栈
- 栈可以通过链表和数组都可以实现,这里是通过链表实现的
package com.basic.example;
import javax.xml.soap.Node;
public class StackExam<Item> {
private Node first;
private int N;
private class Node{
Item item;
Node next;
}
public boolean isEmpty(){return first == null;}
public int size(){return N;}
public void push(Item item){
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public Item pop(){
Item item = first.item;
first = first.next;
N--;
return item;
}
}
2. 队列
- 通常队列是 先进先出
- 在java中可以通过Queue来进行新建一个队列
- 下面是通过链表实现的队列
package com.basic.example;
import javax.xml.soap.Node;
public class QueueExam <Item>{
private Node first ;
private Node last;
private int N;
private class Node{
Item item;
Node next;
}
public boolean isEmpty(){return first == null;}
public int size(){
return N;
}
public void enqueue(Item item){
Node oldlast = last;
last.item = item;
last.next = null;
if (isEmpty()){
first = last;
}else {
oldlast.next = last;
}
}
public Item dequeue(){
Item item = first.item;
first = first.next;
if (isEmpty()){
last =null;
}
N--;
return item;
}
}
3. 背包
- 在java中Bag可以创建
- 背包与前面两个不太一样,
- 首先 他不能够从中删除元素,
- 背包的目的是:帮助用例收集并迭代遍历所有收集 到的元素
- 重要的背包对于处理顺序是不重要的。,
- 下面是实现背包供学习使用
package com.basic.example;
import java.util.Iterator;
public class BagExam<Item> implements Iterable<Item> {
private Node first;
private class Node{
Item item;
Node next;
}
public void add(Item item){
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator1();
}
private class ListIterator1 implements Iterator<Item>{
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public void remove(){}
@Override
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
}