实现单向链表(不带傀儡节点)代码.
import javax.xml.soap.Node;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 21364
* Date: 2021-04-15
* Time: 14:04
*/
//头插法
public class MyLinkedList {
public Node head = null;
//建立一个Node类
class Node {
public int value;
public Node next;
//构造方法,未初始化next的引用,是因为不知道next当前指向哪一个节点
public Node(int value) {
this.value = value;
}
}
//头插法
public void addFirst(int value) {
//根据value值创建一个链表节点(对象)
Node node = new Node(value);
node.next = this.head;
this.head = node;
}
//尾插法
public void addLast(int value) {
Node node = new Node(value);
if (this.head == null) {
this.head = node;
} else {
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
public Node searchFirstIndex(int index) {
Node cur = this.head;
int count = 0;
while (count != index - 1) {
cur = cur.next;
count++;
}
return cur;
}
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index, int value) {
if (index < 0 || index > getLength()) {
System.out.println("插入位置不合法");
return;
}
if (index == 0) {
addFirst(value);
return;
}
if (index == getLength()) {
addLast(value);
return;
}
Node ret = searchFirstIndex(index);
Node node = new Node(value);
node.next = ret.next;
ret.next = node;
}
public int getLength() {
int length = 0;
Node cur = this.head;
while (cur != null) {
length++;
cur = cur.next;
}
return length;
}
//查找key是否包含在单链表中
public boolean contains(int key) {
Node cur = this.head;
while (cur != null) {
if (cur.value == key) {
return true;
}
cur = cur.next;
}
return false;
}
//从头寻找key的前驱
public Node searchPre(int key) {
Node cur = this.head;
while (cur.next != null) {
if (cur.next.value == key) {
return cur;
}
cur = cur.next;
}
return null;
}
//删除第一次出现为key得节点
public void remove(int key) {
if (this.head.value == key) {
this.head = this.head.next;
return;
}
Node prev = searchPre(key);
if (prev == null) {
System.out.println("没有要删除的节点");
return;
}
Node del = prev.next;
prev.next = del.next;
}
//删除所有为key的节点
public void removeAllKey(int key) {
Node cur = this.head.next;
Node prev = this.head;
while (cur != null) {
if (cur.value == key) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur;
this.head = this.head.next;
}
}
}
//打印单链表
public void display() {
Node cur = this.head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
}
//清空单链表
public void clear() {
Node cur = this.head;
while (cur != null) {
Node curNext = cur.next;
cur.next = null;
cur = curNext;
}
this.head = null;
}
}