核心内容:
- Java是如何构造出链表的
- 链表如何进行增删改查
-
双向链表如何构造,以及如何增删元素
单链表:
1. 什么是单链表
单向链表就像一个铁链一样,元素之间相互连接,包含多个结点,每个结点有一个指向后继元素的next指针。表中最后一个元素的next指向null
特点:①缺点:只能连续访问,效率低,但是通过双向链表缓解了该问题②优点:有助于添加元素,扩容方便,没空间限制,不会溢出,可以存储很多个元素。
2.如何在java中创建单链表
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
3.如何对链表进行遍历
对于链表只需要从头节点开始逐个访问
/**
* 链表的遍历
* @param head
* @return
*/
public int getListLength(ListNode head) {
int length = 0;
ListNode listNode = head;
while (head != null) {
length++;
head = head.getNext();
}
return length;
}
4.链表如何插入节点
插入的位置有三种情况头部、中间、尾部
头部:只将插入节点的后继节点指向head(newNode.next=head),然后head重新指向插入节点(head = newNode)
中间:需要先找到要插入位置的前驱节点,将插入节点的指向后继节点,
再将前驱节点的指向插入的节点
尾部:只需要找到最后一个几点指向新节点即可
/**
* 链表的插入
* @param head 头节点
* @param nodeInsert 插入的节点
* @param position 插入的位置从 1 开始
* @return
*/
public ListNode insertNode(ListNode head, ListNode nodeInsert, int position) {
if (head == null) {
//这里可以认为待插入的结点就是链表的头结点,也可以抛出不能插入的异常
return nodeInsert;
}
int size = getListLength(head);
if (position > size + 1 || position < 1) {
System.out.println("位置参数越界");
return head;
}
//插入的位置在头部
if (position == 1) {
nodeInsert.setNext(head);
head = nodeInsert;
return head;
}
//在中间插入
ListNode pHead = head;
int count = 1;
//要在目标位置的前一个节点停下
while (count < position - 1) {
head = head.getNext();
count++;
}
nodeInsert.setNext(head.getNext());
head.setNext(nodeInsert);
return pHead;
}
5.如何删除链表节点
删除链表节点的位置也有三种头部、中间、尾部
头部:只需要head = head,next(将head向前移动一次之后,原来的结点不可达,会被JVM回收掉)
尾部:找到最后一个节点的前驱节点指向null即可
中间:找到要删除节点的前驱preNode,preNode.next = preNode.next.next
/**
* 删除链表的节点
* @param head 头节点
* @param position 删除的位置 1 开始
* @return
*/
public ListNode deleteNode(ListNode head,int position) {
if (head == null) {
return null;
}
int size = getListLength(head);
if (position > size || position < 1) {
System.out.println("参数位置越界");
return head;
}
//当删除第一个节点时
if (position == 1) {
head = head.getNext();
return head;
}
ListNode perHead = head;
int count = 1;
while (count < position - 1) {
perHead = perHead.getNext();
count++;
}
ListNode curNode = perHead.getNext();
perHead.setNext(curNode.getNext());
return head;
}