- 链表的简介
链表是一种这样的数据结构,其中的各对象按线性顺序排列。数组的线性顺序是由数组下标决定的,然而与数组不同的是,链表的顺序是由各个对象里的指针决定的。 - 链表的实现
结点类Node
package sxd.learn.algorithms;
public class Node {
public Node next;
public int data;
public Node(){
}
public Node(int data){
this.data = data;
this.next = null;
}
}
链表类LinkList:
package sxd.learn.algorithms;
/**
* @author Xiaodong date Mar 25, 2015 desc LinkList
*/
public class LinkList {
public Node head;
public LinkList() {
head = new Node();
}
public void add(int data) {
Node node = new Node(data);
Node currentNode = head;
while (currentNode.next != null)
currentNode = currentNode.next;
currentNode.next = node;
}
// 头结点不计入长度
public int length() {
int length = 0;
Node currentNode = head;
while (null != currentNode.next) {
currentNode = currentNode.next;
length++;
}
return length;
}
// 在链表的指定位置之后插入一个节点,链表的位置从0开始
public void insert(int index, int data) {
if (index > this.length()) {
System.out.println("overflow");
return;
}
Node node = new Node(data);
int currentPos = 0;
Node currentNode = head;
while (currentPos != index) {
currentNode = currentNode.next;
currentPos++;
}
node.next = currentNode.next;
currentNode.next = node;
}
public void delete(int index) {
if (index >= this.length()) {
System.out.println("overflow");
return;
}
if (index == 0) {
System.out.println("head node cann't be deleted");
return;
}
int currentPos = 0;
Node currentNode = head;
Node previousNode = head;
while (currentPos != index) {
previousNode = currentNode;
currentNode = currentNode.next;
currentPos++;
}
previousNode.next = currentNode.next;
}
public Node search(int key) {
Node currentNode = head.next;
while (currentNode != null) {
if (currentNode.data == key)
return currentNode;
currentNode = currentNode.next;
}
return null;
}
public void print() {
Node currentNode = head.next;
while (null != currentNode) {
System.out.print(currentNode.data);
currentNode = currentNode.next;
}
System.out.println();
}
}
测试链表类TestLinkList:
package sxd.learn.algorithms;
public class TestLinkList {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkList linklist = new LinkList();
linklist.add(1);
linklist.add(2);
linklist.add(3);
linklist.add(4);
linklist.add(5);
linklist.print();
linklist.delete(1);
linklist.print();
linklist.insert(0, 1);
linklist.insert(1, 6);
linklist.print();
System.out.println(linklist.search(6).data);
}
}