链式线性表是数据结构里很简单但也是很常见的数据结构,相比顺序存储的线性表,可以更快的实现添加和删除操作,但读取速度比顺序结构会慢。链式线性表的关键在于,每个数据存储为节点形式。不仅仅保存有数据,还有一个引用“next”指向下一个节点。链式结构还可以再扩展为双向链表、循环链表等等。基本原理一样,只是增加了引用。下面就是最简单的链式线性表的实现的源代码,会有潜在的bug,不然人人都可以写底层数据结构啦!但是不影响我们理解这种数据结构:
package mywork.c20150605;
import mywork.c20150605.LinkList.Node;
/*
* a simple demo for LinkList
* HanChun 2015.6.5
*/
public class LinkListDemo<T> {
class Node{
T data;
Node next;
public Node(){
}
public Node(T data, Node next){
this.data = data;
this.next = next;
}
}
Node header;
Node tail;
int size; //记录纤线性表长度
public LinkListDemo(){
header = null;
tail = null;
}
public LinkListDemo(Node element){
header = element;
tail = header;
size++;
}
//返回线性表大小
public int getSize(){
return size;
}
//判断线性表是否为空
public boolean isEmpty(){
if(size == 0){
return true;
}
return false;
}
//返回索引处节点
public Node getNodeByIndex(int index){
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("索引越界");
}
Node current = header;
for(int i = 0; i < size && current != null; current = current.next, i++){
if(i == index){
return current;
}
}
return null;
}
//返回值在线性表中第一个位置
public int locate(T element){
Node current = header;
for(int i = 0; i < size && current != null; current = current.next, i++ ){
if(current.data.equals(element)){
return i;
}
}
return -1;
}
/*
* 之所以要强调头尾节点处的情况,是因为:头尾节点直接影响
* 后面对链式线性表的操作,如果是在中间插入,对头尾引用是
* 没有影响的。
*/
public void addAtHeader(T element){
header = new Node(element, header);
if(tail == null){
tail = header;
}
size++;
}
//在表尾插入元素
public void add(T element){
if(header == null){
header = new Node(element, null);
tail = header;
}else{
Node newNode = new Node(element, null);
tail.next = newNode;
tail = newNode;
}
size++;
}
//在指定位置插入节点
public void insert(T element, int index){
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("索引越界");
}
if(header == null){
add(element);
}else{
if(index == 0){
addAtHeader(element);
}else{
Node prev = getNodeByIndex(index - 1);
prev.next = new Node(element, prev.next);
}
}
size++;
}
/*
* 删除指定位置节点,该方法有待完善,比如删除的线性表是空的,很明显
* 这段代码会抛出NuLLPointException
*/
public void delete(int index){
if(index < 0 || index > size){
throw new IndexOutOfBoundsException("索引越界");
}
if(index == 0){
header = header.next;
}else{
Node prev = getNodeByIndex(index - 1);
Node del = prev.next;
prev.next = del.next;
del = null;
}
size--;
}
public String toString(){
if(isEmpty()){
return "[]";
}
StringBuilder sb = new StringBuilder("[");
for(Node current = header; current != null ; current = current.next){
sb.append(current.data.toString() + ",");
}
int len = sb.length();
return sb.delete(len-1, len).append("]").toString();
}
}