Java链表根据逻辑结构有单链表,双向链表,循环链表,双向循环链表,松散链表等等,本篇文章重点描述java的单链表。
链表节点以类listNode表示,其属性有数据域data和下一个节点next
private int data;
private ListNode next;
下面是链表的相关操作
/**
@author xgz
@date 创建时间:2019年7月31日 上午10:53:02
@version 1.0
单向链表的相关操作
*/
public class LinkList {
//向链表中插入元素 时间复杂度O(n),空间复杂度O(1)
ListNode InsertLinkedList(ListNode headNode, ListNode nodeToInsert ,int position) {
if(headNode == null) { //链表为空
return nodeToInsert;
}
int size = GetListLength(headNode);
if(position > size + 1 ||position < 1) { //越界
throw new IndexOutOfBoundsException("Index: " + position + ", Size: " + size);
}
if(position == 1) { //在链表开头插入
nodeToInsert.setNext(headNode);
return nodeToInsert;
}else { //在链表中间或者尾部插入
ListNode previouseNode = headNode; //前一个节点
int count = 1;
while(count < position -1) { //找到position前一个节点
previouseNode = previouseNode.getNext();
count ++;
}
ListNode currentNode = previouseNode.getNext(); //position节点
nodeToInsert.setNext(currentNode);
previouseNode.setNext(nodeToInsert);
}
return headNode;
}
/**
*
@Description:删除链表中的节点 时间复杂度O(n),空间复杂度O(1)
@parameter 参数及其意义
@return 返回值
@throws 异常类及抛出条件
*/
ListNode DelectLinkedListNode(ListNode headNode,int position) {
if(headNode == null) { //链表为空
System.out.println("链表为空");
return null;
}
int size = GetListLength(headNode);
if(position > size + 1 ||position < 1) { //越界
throw new IndexOutOfBoundsException("Index: " + position + ", Size: " + size);
}
if(position == 1) { //删除第一个节点
ListNode currentNode = headNode.getNext();
headNode = null;
return currentNode;
}else { //删除链表中间或者尾部节点
ListNode previouseNode = headNode; //前一个节点
int count = 1;
while(count < position -1) { //找到position前一个节点
previouseNode = previouseNode.getNext();
count ++;
}
ListNode currentNode = previouseNode.getNext(); //position节点
previouseNode.setNext(currentNode.getNext());
currentNode = null;
}
return headNode;
}
/**
*
@Description:返回链表的长度
@parameter 参数及其意义
@return 返回值
@throws 异常类及抛出条件
*/
int GetListLength(ListNode headNode) {
int length = 0;
ListNode currentNode = headNode;
while(currentNode != null) {
length ++;
currentNode = currentNode.getNext();
}
return length;
}
/**
*
@Description:清空整个链表 时间复杂度O(n),空间复杂度O(1)
定义临时变量,得到Next节点,使当前节点为null
@parameter 参数及其意义
@return 返回值
@throws 异常类及抛出条件
*/
void clearListLinked(ListNode headNode) {
ListNode auxiaryNode,iterator = headNode;
while(iterator != null) {
auxiaryNode = iterator.getNext(); //临时变量
iterator = null; // 自动垃圾回收
}
}
//初始化 传入的节点头节点,这里我们创建的链表是带头结点的,头结点不带信息,方便与链表操作
public ListNode Initlink(ListNode node) { //初始化节点
node=new ListNode();
node.setNext(null);
return node;
}
//打印链表
public void Printl(ListNode headNode) {
ListNode node=headNode;
while(node!=null) {
System.out.println(node.getData());
node=node.getNext();
}
}
}