我的这个Demo一共只有两个类,一个Node,一个MyLinkedList。前一个是用来的表示结点的,后一个是测试。
先把代码弄上来:
package com.hust.datastruct; //这是一个节点信息类 public class Node { Node next = null; int data; public Node(int data) { this.data = data; } }
package com.hust.datastruct; //测试类 public class MyLinkedList { // 链表头的引用 Node head = null; /** * 向链表中插入数据 * * @param d * :插入的数据内容 */ public void addNode(int d) { Node newNode = new Node(d); // 如果链表头是null,则当前插入这个数据就是表头 if (head == null) { head = newNode; return; } // 查找最后一个为空的Node节点 Node tmp = head; while (tmp.next != null) { tmp = tmp.next; // 防止添加重复数据 if (tmp.data == d) { return; } } // 然后把新的数据添加在这个空的节点上面 tmp.next = newNode; }
/**
* [@param](http://my.oschina.net/u/2303379) index
* :删除第index个节点
* [@return](http://my.oschina.net/u/556800) 成功返回true,失败返回false
*/
public Boolean deleteNode(int index) {
if (index < 1 || index > length()) {
return false;
}
if (index == 1) {
head = head.next;
return true;
}
int i = 1;
Node preNode = head;
Node curNode = preNode.next;
while (curNode != null) {
if (i == index) {
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
/**
* [@return](http://my.oschina.net/u/556800) 返回节点的长度
*/
public int length() {
int length = 0;
Node tmp = head;
while (tmp != null) {
length++;
tmp = tmp.next;
}
return length;
}
/**
* 排序的规则是按存储数据的从小到大
*
* [@return](http://my.oschina.net/u/556800) 返回排序后的头节点
*/
public Node orderNode() {
Node nextNode = null;
int temp = 0;
Node curNode = head;
while (curNode.next != null) {
nextNode = curNode.next;
while (nextNode != null) {
if (curNode.data > nextNode.data) {
temp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
/**
* 打印链表
*/
public void printList() {
Node tmp = head;
while (tmp != null) {
System.out.print(tmp.data+" ");
tmp = tmp.next;
}
}
// 测试方法
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addNode(5);
list.addNode(3);
list.addNode(1);
list.addNode(3);
System.out.println("listLen=" + list.length());
System.out.println("Order before:");
list.printList();
list.orderNode();
System.out.println("\nOrder after:");
list.printList();
}
}
里面的方法都有最简单的注释。