一、链表的定义:
链表是一种物理存储结构上非连续存储结构。
二、节点的表示:
节点(Node)==>数据+补充信息
三、单链表的插入:
1、头插法
2、尾插法
3、任意位置插入
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
//头插法
public void addFirst(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
node.next = head;
head = node;
}
//尾插法
public void addLast(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
Node tail = head;
while (tail.next != null) {
tail = tail.next;
}
tail.next = node;
}
//任意位置插入,第一个数据节点为0号下标
public boolean addIndex(int index, int data) {
int size = getSize();
if (index < 0 || index > size) {
return false;
}
if (index == 0) {
addFirst(data);
return true;
}
if (index == size) {
addLast(data);
return true;
}
Node node = new Node(data);
Node prev = getPos(index - 1);
node.next = prev.next;
prev.next = node;
return true;
}
//获得节点总个数
private int getSize() {
int size = 0;
for (Node cur = head; cur != null; cur = cur.next) {
size++;
}
return size;
}
// 给定 index 下标, 找到对应的节点
private Node getPos(int index) {
Node cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur;
}
}
四、单链表的删除操作:
1、删除第一次出现关键字为toRemove的节点。
2、删除所有值为toRemoveAll的节点。
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
//删除第一次出现关键字为toRemove的节点
public void remove(int toRemove) {
if (head.data == toRemove) {
head = head.next;
return;
}
Node prev = searchPrev(toRemove);
Node toDelete = prev.next;
prev.next = toDelete.next;
}
private Node searchPrev(int toRemove) {
for (Node cur = head; cur != null && cur.next != null; cur = cur.next) {
if (cur.next.data == toRemove) {
return cur;
}
}
return null;
}
//删除所有值为toRemoveAll的节点
public void removeAll(int toRemove) {
Node prev = head;
Node cur = head.next;
while (cur != null) {
if (cur.data == toRemove) {
prev.next = cur.next;
cur = prev.next;
} else {
prev = cur;
cur = cur.next;
}
}
if (head.data == toRemove) {
head = head.next;
}
}
}
五、单链表的查找操作:
查找是否包含关键字toFind是否在单链表中
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
public boolean contains(int toFind) {
for (Node cur = head; cur != null; cur = cur.next) {
if (cur.data == toFind) {
return true;
}
}
return false;
}
}
六、单链表清空操作:
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
public void clear() {
head = null;
}
}