最近在学习LinkedList的相关知识,中间有用到链表,在看了JAVA3y大哥的文章后收到启发,也想自己实现一下,中间为了
简单起见用int变量来表示数据。
自定义了一个类用来表示链表的节点
public class Node {
//为了方便属性变量都定义为public;数据为简单起见,采用int类型
public int data;
//指向下一个节点,默认为null
public Node next;
public Node(int data){
this.data = data;
}
public Node() {
}
}
为了方便我在测试主类中定义了两个属性,head用来表示链表的头节点,length属性记录链表长度。
private static final Node head = new Node();
private static int length = 0;
1.向链表中增加节点 addFirstNode方法
/**
* 增加节点,此处采用的是头插法
* @param node
*/
public void addFirstNode(Node node){
length++;
Node temp = head;
if(head.next != null){
node.next = temp.next;
}
head.next = node;
}
2.向链表指定位置插入节点
/**
* 在指定位置增加节点
* @param node
* @param pos
*/
public void addNodeToPos(Node node,int pos){
if(pos > length()){
System.out.println("插入位置不合法!");
return;
}
int index = 1; //下标从1开始
Node temp = head;
while(index < pos){
temp = temp.next;
index++;
}
if(index == pos){
node.next = temp.next;
temp.next = node;
}
length++;
}
3. 删除指定位置的节点
/**
* 删除指定位置的节点
*/
public void delNodePos(int pos){
int index = 1;
Node temp = head;
if(pos > length||pos < 1){return;}
while(index <= pos -1){
temp = temp.next;
index ++;
}
temp.next = temp.next.next;
length--;
}
4. 使用冒泡排序法对链表进行排序
/**
* 使用冒泡排序法则对链表进行排序
*/
public void bublesort(){
if(head.next == null){return;}
Node cur = head; // 当前节点
Node tail = null,tmp = null;
while(cur.next != tail){
while(cur.next != tail){
if(cur.data >cur.next.data){
int tmpData = cur.data;
cur.data = cur.next.data;
cur.next.data = tmpData;
}
cur = cur.next;
}
tail = cur;
cur = head;
}
}
5.使用选择排序法对链表进行排序
/**
* 使用选择排序对链表进行排序
*/
public void selectSort(){
Node temp = head;
Node secondTemp = null;
while(temp.next != null){
secondTemp = temp.next;
while(secondTemp != null){
if(temp.data >secondTemp.data){
int td = temp.data;
temp.data = secondTemp.data;
secondTemp.data = td;
}
secondTemp = secondTemp.next;
}
temp = temp.next;
}
}
6.返回链表长度,此处可以直接返回测试主类中的length,也可遍历整个链表进行检索
/**
* 通过遍历链表的方式来返回链表的长度
*/
public int length(){
//循环遍历整个链表,将长度叠加返回即可
Node temp = head;
int len =0;
while(temp.next != null){
temp =temp.next;
len++;
}
return len;
}
7.打印链表中的元素
/**
* 从头开始打印链表中各节点的数据
*/
public void print(){
Node temp = head;
while(temp.next != null){
System.out.print(temp.next.data+",");
temp = temp.next;
}
System.out.println();
}
参考资料:https://cnblogs.com/whgk/p/6589920.html
https://cnblogs.com/bywallance/p/6726251.html