单链表的简单实现

1、单链表的存储结构

/**
* 单链表
* @author fox
*
*/
public class Node {
private Object nodeValue;
private Node nextNode;

public Node() {
nodeValue = null;
nextNode = null;
}

public Node(Object item) {
nodeValue = item;
nextNode = null;
}

public Node(Object item, Node next) {
nodeValue = item;
nextNode = next;
}

public Object getNodeValue() {
return nodeValue;
}

public void setNodeValue(Object nodeValue) {
this.nodeValue = nodeValue;
}

public Node getNextNode() {
return nextNode;
}

public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}

}

2、由于单链表是一种线性结构,所以他实现了LinearList接口。
关于LinearList接口,详情请查看[url]http://fox-ed.iteye.com/blog/1775542[/url]
详细实现方法如下:

/**
* 单链表的实现
* @author fox
*
*/
public class SingleLinkList implements LinearList {

private Node head;
public SingleLinkList() {
head = null;
}

public SingleLinkList(Node node) {
this.head = node;
}

public boolean isEmpty() {
if(head == null) {
return true;
} else {
return false;
}
}

public int size() {
int size = 0;
Node temp = this.head;
while(temp != null) {
size++;
temp = temp.getNextNode();
}
return size;
}

public Object get(int index) {
checkIndex(index);
Node temp = this.head;
for(int i = 0; i < index; i++) {
temp = temp.getNextNode();
}
return (Object)temp.getNodeValue();
}

public void set(int index, Object o) {
checkIndex(index);
Node node = this.head;
for(int i = 0; i < index; i++) {
node = node.getNextNode();
}
node.setNodeValue(o);
}

public boolean add(int index, Object o) {
if(index < 0) {
throw new IndexOutOfBoundsException("下标错误:"+index);
}

if(head == null) {
head = new Node(o);
} else {
Node temp = this.head;
if(index == 0) {
this.head = new Node(o,temp);
} else {
int i =0;
while(temp.getNextNode() != null && i < index - 1) {
i++;
temp = temp.getNextNode();
}
temp.setNextNode(new Node(o,temp.getNextNode()));
}
}
return true;
}

public boolean add(Object o) {
return add(Integer.MAX_VALUE,o);
}

public Object remove(int index) {
checkIndex(index);
Object oldObj = null;
Node temp = this.head;
if(index == 0) {
oldObj = (Object)head.getNodeValue();
this.head = temp.getNextNode();
temp = null;
} else {
int i = 0;
while(temp.getNextNode() != null && i < index - 1) {
i++;
temp = temp.getNextNode();
}
Node node = temp.getNextNode();
oldObj = (Object) node.getNodeValue();
temp.setNextNode(node.getNextNode());
node = null;
}
return oldObj;
}

public void clear() {
int size = this.size();
if(size != 0) {
for(int i = size - 1;i >= 0; i--) {
this.remove(i);
}
}
}

private void checkIndex(int index) {
if(index < 0 || index > this.size() - 1) {
throw new IndexOutOfBoundsException("下标错误:"+index);
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值