【链表】
1.实现链表
public class Node
{
Item item;//Item 表示想用的任意数据类型
Node next;
}
2.插入结点
①表头插入:
第一步 保存好首节点
第二步 设置新结点
第三步 让保存好的首节点指向新结点
Node oldFirst = first;
first = new Node();
first.item=110;
first.next = oldfirst;
②表尾插入
Node oldLast = last;
last = new Node();
last.item=70;
oldLast.next=last;
3.删除结点
表头删除
first = first.next
4.遍历
for(Node x =first ; x!=null ; x=x.next)
{
//处理x.item
}
【栈、队列】
1.两者特点比较
①栈:先进先出
②队列:后进先出
2.栈的实现
public class Stack<Item> {
private Node first;
private int N;//记录栈中元素个数
private class Node
{
Item item;
Node next;
}
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;
}
public boolean isEmpty() {
return first==null;
}
public int size() {
return N;
}
}
3.队列的实现
public class Queue<Item>
{
private Node first;
private Node last;
private int N;
private class Node
{
Item item;
Node next;
}
public boolean isEmpty()
{
return first==null;
}
public void enqueue(Item item)
{
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if(isEmpty())
first = last;
else
oldLast.next = last;
N++;
}
public Item dequeue()
{
Item item = first.item;
first = first.next ;
if(isEmpty())
last = null;
N--;
return item;
}
public int size() {
return N;
}
}