1.节点的创建
package linkedList;
public classNode {
Node next=null;
intdata;
publicNode(int data){
this.data=data;
}
}
2.添加节点,删除节点,打印节点,求节点的长度,对节点进行排序。
package linkedList;
public classMylinkedList {
publicstatic void main(String[] args) {
MylinkedList mylist = new MylinkedList();
mylist.addData(5);
mylist.addData(3);
mylist.addData(2);
System.out.println("mylist="+ mylist.length());
mylist.printList();
System.out.println();
mylist.deleteNode(2);
System.out.println("mylist="+mylist.length());
mylist.orderList();
mylist.printList();
}
Node head = null; // 链表头的引用
/**
* 向链表中插入数据 param d:插入数据的内容
*/
publicvoid addData(int d) {
Node s = new Node(d);
if (head == null) {
head = s;
return;
}
Node tmp = head;
while (tmp.next != null){
tmp = tmp.next;
}
// 添加节点到结束位置
tmp.next = s;
}
/**
* 返回节点的长度
*/
publicint length() {
int length = 0;
Node tmp = head;
while (tmp != null){
length++;
tmp = tmp.next;
}
return length;
}
/**
* 删除第index个节点return成功返回true,失败返回false
*/
publicboolean deleteNode(int index) {
// 删除元素的位置不合理
if (index < 1 || index > length()) {
return false;
}
// 删除链表第一个元素
if (index == 1) {
head = head.next;
return true;
}
int i = 2;
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;
}
/**
* 打印链表
*/
publicvoid printList() {
Node tmp = head;
while (tmp != null){
System.out.print(tmp.data);
tmp = tmp.next;
}
}
/**
* 对链表进行排序
*/
publicNode orderList() {
Node curNode = head;
Node nextNode = null;
int tmp = 0;
while (curNode != null){
nextNode = curNode.next;
while (nextNode != null){
if (curNode.data > nextNode.data) {
tmp = curNode.data;
curNode.data =nextNode.data;
nextNode.data = tmp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
}