标签:
知识点:1、使用内部类构造节点 http://www.cnblogs.com/dolphin0520/p/3811445.html ;
2、节点 = 数据域+指针域 Java中是用引用来代替指针 ;
3、头节点是只有first引用变量,没有Object;
4、插入和删除都是需要遍历。current=current.next
package database;
//三要素: 头节点 节点类(数据域和引用域) 大小(位置)
public class LinkedList {
private class Node {
private Object obj; // 数据域
private Node next; // 指针域,Java是用引用来代替指针
private Node(Object obj) {
this.obj = obj;
}
}
// 插入头节点,obj = null ;
private Node first;
private int pos; // 位置
// 头节点的值为null
public LinkedList() {
this.first = null;
}
// 在表头插入节点,即头插法。而不是在表尾操作~!!!!!!
public void insertFirst(Object obj) {
Node node = new Node(obj);
node.next = first; // ??????
first = node;
}
// 删除第一个节点 , 而不是头节点(只有一个引用first)
public Node removeFirst() throws Exception {
if (first == null)
throw new Exception("list is empty!");
Node temp = first;
first = first.next;
return temp;
}
// 根据数据寻找节点
public Object searchNode(Object obj) throws Exception {
if (first == null)
throw new Exception("LinkedList is empty!");
Node cur = first;
while (cur != null) {
if (cur.obj.equals(obj))
return cur.obj;
cur = cur.next;
}
return null; // 若是不存在,就直接返回null
}
// 链表的长度
public int linkLength() {
Node current = first;
int length = 0;
while (current != null) {
current = current.next;
length++;
}
return length;
}
// 根据位置寻找节点
public Node findByPos(int index) {
Node current = first;
if (pos != index) {
current = current.next;
pos++;
}
return current;
}
// 删除某节点 ,遍历删除;
public void removeNode(Object obj) throws Exception {
if (searchNode(obj).equals(null)) {
throw new Exception("obj is not exit!");
}
if (first.obj.equals(obj)) {
first = first.next;
} else {
Node pre = first;
Node current = first.next;
while (current != null) {
if (current.obj.equals(obj)) {
pre.next = current.next;
} else {
pre = current;
current = current.next;
}
}
}
}
// 在某点后插入节点
public void insertNode(int index, Object obj) {
Node insertNode = new Node(obj);
Node current = first;
int pos = 0;
if (index == 0) {
insertNode.next = first;
first = insertNode;
} else {
while (index != pos) {
current = current.next;
pos++;
}
insertNode.next = first.next;
first.next = insertNode;
pos = 0;
}
}
// 删除任意位置的节点
// 判断是否为空
public boolean isEmpty() {
return (first == null);
}
// 输出链表
public void display() {
if (first == null)
System.out.println("empty");
Node cur = first;
while (cur != null) {
System.out.print(cur.obj.toString() + " -> ");
cur = cur.next;
}
System.out.print("\n");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
标签:
原文地址:http://www.cnblogs.com/neversayno/p/5071300.html