链表
1.逻辑上有前后顺序
2.不保证逻辑前后顺序元素挨着
以下介绍几个最基础的链表操作:
首先定义Node类:
class Node{
public int value;
public Node next;
public Node(int value){
this.value = value;
this.next = null;
}
}
一、插入
链表的遍历
public static void displayLinkedList(Node head){
for(Node cur = head ; cur != null; cur = cur.next){
System.out.printf("%d -->",cur.value);
}
System.out.println("null")
}
头插
- 创建新节点
- 新节点的next = 原头结点
- 更新头结点为新结点:此时要将新节点作为一个返回值,不可以把newNode赋值给head,因为head是形参,修改时不会对实参有影响。
public static Node pushFront(Node head, int value){
Node newNode = new Node(value);
newNode.next = head;
return newNode;
}
空的链表:一个节点都没有
尾插
分情况讨论:链表中有元素和链表中无元素
- 空链表尾插:视为头插
- 非空链表尾插:
(1)创建新节点
(2)找到链表中最后一个节点,将最后一个节点的next指向新节点
public static Node getLast(Node head){
Node cur = head;
while(cur.next != null ){
cur = cur.next;
}
return cur;
}
public static Node pushBack(Node head, int value){
if(head == null){
return pushFront(head,value); //链表为空
}else{
Node newNode = new Node(value); //链表不为空
Node last = getLast(head);
last.next = newNode;
return head;
}
}
二、删除
头删
- 如果链表为空,返回null
- 如果链表不为空,将头节点改为原本头节点的next节点
public static Node popFront(Node head){
if (head == null){
System.out.printf("参数不合法%n");
return null;
}
return head.next;
}
尾删
- 如果链表为空报错,如果链表只有一个结点直接返回null
- 如果链表不为空,找到链表中倒数第二个结点,将倒数第二个结点next置为null
public static Node getLastLast(Node head){
Node cur = head;
while(cur.next.next != null){
cur = cur.next;
}
return cur;
}
public static Node popBack(Node head){
if (head == null){
System.out.printf("参数不合法%n");
return null;
}
if (head.next == null){
return null;
}else {
Node lastLast = getLastLast(head);
lastLast.next = null;
return head;
}
}