链表
1.创建链表
package com.zzw.链表;
/**
* 非常基本的单项链表
* @author john
*
*/
public class Node {
Node next=null;
int data;
public Node(int d) {
data=d;
}
/*
* 添加一个结点
*/
void appendToTail(int d){
Node end=new Node(d);
Node n=this;
while(n.next!=null){
n=n.next;
}
n.next=end;
}
/*
* 删除单向链表中的结点
*/
Node deleteNode(Node head,int d){
Node node=head;
if(node.data==d){
return head.next;//表头指向下一个结点
}
while(node.next!=null){
if (node.next.data==d) {
node.next=node.next.next;
return head;//表头不变
}
node=node.next;
}
return head;
}
}
2.栈
package com.zzw.链表;
/**
* 实现一个 栈
* @author john
* 栈采用后进先出(LIFO-last in first out )的顺序,就像一堆盘子,最后入栈的元素最先出栈---栈也可以用链表实现
* -用户通常只能看到栈顶的元素
*/
public class Stack {
Node top;
//出栈
Object pop(){
if (top!=null) {
Object item=top.data;
top=top.next;
return item;
}
return null;
}
//入栈
void push(Object item){
Node t=new Node((int)item);
t.next=top;
top=t;
}
//获取栈顶元素的数据
Object peek(){
return top.data;
}
}
3.队列
package com.zzw.链表;
/**
* 实现一个队列
*
* @author john 队列采用先进先出(FIFO-first in,first out)的顺序,就像食堂买饭的队列.
*/
public class Queue {
Node firstNode, lastNode;
/*
* 入栈
*/
void enqueue(Object item) {
if (firstNode == null) {
lastNode = new Node((int) item);
firstNode = lastNode;
} else {
lastNode.next = new Node((int) item);
lastNode = lastNode.next;
}
}
/*
* 出栈
*/
Object dequeue() {
if (firstNode != null) {
Object item = firstNode.data;
firstNode = firstNode.next;
return item;
}
return null;
}
}