单链表
单链表中有多个节点,每个节点包括两个属性,一个是当前值(value),另一个是指向一个节点的指针(next)。
public class Node {
int value;
Node next;
public Node() {
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node(int value) {
this.value = value;
}
public Node(Node next) {
this.next = next;
}
}
添加元素
1.头部插入
创建一个新节点newNode,并将next指向头节点head(newNode.next = head),最后将newNode赋值给head,使head继续指向链表中第一个节点。
public Node insertNode(Node head, Node nodeInsert) {
if (head == null) { //判断链表是否为空
return nodeInsert;
}
nodeInsert.next = head;
head = nodeInsert;
return nodeInsert;
}
2.中间插入
首先要找到插入的位置,当前节点的下一个节点(cur.next)为新节点插入的位置,先将新节点(newNode)指向当前节点的下一个节点(newNode.next = cur.next),然后再将当前节点(cur)的下一个节点指向新节点(cur.next = newNode)
public Node insertNode(Node head, Node nodeInsert, int position) {
// 链表是否为空
if (head == null) {
return null;
}
// 判断是否越界
int size = getLength(head);
if (position < 1 || position > size + 1) {
return null;
}
// 找到插入位置
Node cur = head;
int count = 1;
while (count < position - 1) {
count++;
cur = cur.next;
}
// 插入结点
nodeInsert.next = cur.next;
cur.next = nodeInsert;
return head;
}
3.尾部插入
找到最后一个节点,并将它指向新节点(last.next = newNode),最后将新节点指向null(newNode.next = null).
public Node insertIntoTail(Node head, Node newNode) {
//判断链表是否为空
if (head == null) {
return null;
}
Node last = head;
//找到最后一个节点
while (last.next != null) {
last = last.next;
}
last.next = newNode;
newNode.next = null;
return head;
}
链表删除
1.头部删除
将头节点(head)指向下一个节点(head = head.next)。
public Node insertNode(Node head) {
if (head == null) { //判断链表是否为空
return nodeInsert;
}
head = head.next;
return head;
}
2.中间删除
先找到要删除节点的上一个节点(cur),将这个节点指向要删除节点的下一个节点(cur.next = cur.next.next)进行删除
public Node insertNode(Node head, Node nodeInsert, int position) {
// 链表是否为空
if (head == null) {
return null;
}
// 判断是否越界
int size = getLength(head);
if (position < 1 || position > size + 1) {
return null;
}
// 找到删除位置
Node cur = head;
int count = 1;
while (count < position - 1) {
count++;
cur = cur.next;
}
// 删除结点
cur.next = cur.next.next;
return head;
}
3.尾部删除
找到倒数第二个节点(cur.next.next == null)并将它指向null(cur.next = null)
public Node insertIntoTail(Node head) {
//判断链表是否为空
if (head == null) {
return null;
}
Node last = head;
//找到最后一个节点
while (last.next.next != null) {
last = last.next;
}
last.next = null;
return head;
}