单链表java实现机制图
当插入第一个节点是 head指向该节点
当在插入一个节点时,head执行新的dataNode节点,从这点可以看出,最先加入的节点为head节点
其java 实现代码为
package cn.com;
public class 单链表 {
//头节点
public Node firstHead;
/**
* 插入数据
* @param data
*/
public void insert(Object data){
Node node = new Node();
node.setData(data);
if(firstHead == null){
node.nextNode = null;
}
else{
node.nextNode = firstHead;
}
firstHead = node; //新加入的节点为head节点
}
public Object find(Object data){
if(firstHead == null){
throw new NullPointerException("链表为空");
}
Node temp = firstHead;
while(temp != null ){
if(temp.data.equals(data)){
return temp.data;
}
temp = temp.nextNode;
}
return null;
}
public void remove(Object data){
if(firstHead == null){
throw new NullPointerException("链表为空");
}
if(firstHead.data.equals(data)){//如果刚好是第一个节点
//指针直接指向第二个节点
firstHead = firstHead.nextNode;
}
else{
//当前结点为下一个节点
Node curr = firstHead.nextNode;
//前一个节点
Node pre = firstHead;
while(curr != null){
if(curr.data.equals(data)){ //如果就是当前结点
pre.nextNode = curr.nextNode;
return;
}
else{
pre = curr;
curr = curr.nextNode;
}
}
}
}
/**
* 定义链表中的节点
* @author wanhonghui
*
*/
public class Node{
//下一个节点
private Node nextNode;
//存放的数据
private Object data;
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
}
package cn.com;
public class 单链表测试类 {
public static void main(String[] args) {
单链表 link = new 单链表();
link.insert("第一个节点");
link.insert("第二个节点");
link.insert("第三个节点");
System.out.println(link.firstHead.getData());
System.out.println(link.firstHead.getNextNode().getData());
System.out.println(link.firstHead.getNextNode().getNextNode().getData());
}
}
结果为:
第三个节点
第二个节点
第一个节点
package cn.com;
public class 单链表测试类 {
public static void main(String[] args) {
单链表 link = new 单链表();
link.insert("第一个节点");
link.insert("第二个节点");
link.insert("第三个节点");
// System.out.println(link.firstHead.getData());
// System.out.println(link.firstHead.getNextNode().getData());
// System.out.println(link.firstHead.getNextNode().getNextNode().getData());
System.out.println(link.find("第二个节点"));
}
}
结果为:
第二个节点
package cn.com;
public class 单链表测试类 {
public static void main(String[] args) {
单链表 link = new 单链表();
link.insert("第一个节点");
link.insert("第二个节点");
link.insert("第三个节点");
link.remove("第二个节点");
System.out.println(link.firstHead.getData());
System.out.println(link.firstHead.getNextNode().getData());
System.out.println(link.firstHead.getNextNode().getNextNode().getData());
}
}
结果为:
第三个节点
第一个节点
Exception in thread "main" java.lang.NullPointerException
at cn.com.单链表测试类.main(单链表测试类.java:14)
总结说明:
在表头插入一个新的链接点,时间复杂度为O(1)
查找包含指定关键字的链接点,由于需要遍历查找,平均需要查找N/2次,即O(N)
删除包含指定关键字的链接点,由于需要遍历查找,平均需要查找N/2次,即O(N)