1.链表的结构如下:
2.链表中节点的删除:
删除节点的步骤:
(1)根据索引找到需要删除的节点;
(2)将该节点的前一个节点preNode和后一个节点nextNode保存下来;
(3)nextNode.PreNode = preNode; preNode.NextNode = nextNode;
3.链表中节点的添加:
添加节点的步骤(中间添加):
(1)根据索引找到需要添加的位置;
(2)temp.NextNode = temp.PreNode.NextNode;
temp.PreNode = temp.NextNode.PreNode;
temp.PreNode.NextNode = temp;
temp.NextNode.PreNode = temp;
/**
*
*/
package com.sunlei;
/**
*@author 作者:sunlei
*@version 创建时间:2018年3月1日上午11:49:42
*说明
*/
public class MyLinkedList {
private Node first;
private Node last;
private int size;
public int size() {
return size;
}
public void add(Object obj) {
Node n = new Node();
if(null == first) {
n.PreNode = null;
n.Obj = obj;
n.NextNode = null;
first = n;
last = n;
}else {
n.PreNode = last;
n.Obj = obj;
n.NextNode = null;
last.NextNode = n;
last = n;
}
size++;
}
public void add(int index,Object obj) {
rangeCheck(index);
Node temp = node(index);
temp.Obj = obj;
if(null != temp) {
temp.NextNode = temp.PreNode.NextNode;
temp.PreNode = temp.NextNode.PreNode;
temp.PreNode.NextNode = temp;
temp.NextNode.PreNode = temp;
size++;
}
}
public Node node(int index) {
rangeCheck(index);
Node temp = null;
if(null != first) {
temp = first;
for(int i=0;i<index;i++) {
temp = temp.NextNode;
}
}
return temp;
}
public Object get(int index) {
rangeCheck(index);
Node temp = node(index);
if(null != temp) {
return temp.Obj;
}else {
return null;
}
}
public void remove(int index) {
rangeCheck(index);
Node temp = node(index);
if(null != temp) {
Node preNode = temp.PreNode;
Node nextNode = temp.NextNode;
nextNode.PreNode = preNode;
preNode.NextNode = nextNode;
size--;
}
}
public void rangeCheck(int index) {
if(index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add(1,"BBB");
System.out.println(list.size());
System.out.println(list.get(1));
}
class Node{
Node PreNode;
Object Obj;
Node NextNode;
public Node() {
}
public Node(Node PreNode,Object Obj,Node NextNode) {
super();
this.PreNode = PreNode;
this.Obj = Obj;
this.NextNode = NextNode;
}
}
}
优化查找节点,链表中查找总是从第一个开始索引太浪费,选择判断需要索引的节点的范围是在链表的前半部分还是后半部分,如果在前半部分,从头索引,如果在后半部分,从最后开始索引,改进如下:
public Node node(int index) {
rangeCheck(index);
Node temp = null;
if(null != first) {
if(index < (size >> 1)) {
temp = first;
for(int i=0;i<index;i++) {
temp = temp.NextNode;
}
}else {
temp = last;
for(int i=size-1;i>index;i--) {
temp = temp.PreNode;
}
}
}
return temp;
}