话不多说,有注释
import com.sun.deploy.net.proxy.ProxyUnavailableException;
class Node {//节点类
public int data;
public Node next;
public Node() {
}
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class SingleLinkedList {//单链表本身是一种类
//由节点来构成单链表,
public Node head;//头节点
public SingleLinkedList() {
this.head = null;
}
//头插法
public void addFirst(int data) {
Node node = new Node(data);
if(this.head == null) {
this.head = node;
return;
}
node.next = this.head;
this.head = node;
}
//尾插法
public void addLast(int data) {
Node node = new Node(data);
if(this.head == null) {
this.head = node;
return;
}
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
private int findIndex(int index) {
int count = 0;
Node node = new Node();
node = this.head;
while(count < index-1) {
node = node.next;
count++;
}
return count;
}
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index,int data) {
Node node = new Node(data);
Node prev = this.head;
if(index < 0 || index >size()) {
throw new RuntimeException("位置不合法");
}
if(index == 0) {
addFirst(data);
return;
}
if(index == size()) {
addLast(data);
return;
}
//先让pre走到index-1处
for (int i = 0; i < findIndex(index); i++) {
prev = prev.next;
}
//然后先连接后面的,再连接前面的
node.next = prev.next;
prev.next = node;
}
//查找是否包含关键字key是否在单链表当中
public boolean contains(int key){
Node cur = this.head;
while(cur != null) {
if(cur.data == key) {
return true;
}
cur = cur.next;
}
return false;
}
//删除第一次出现关键字为key的节点方法一
private Node findPrev(int key) {
Node prev = this.head;
while (prev.next != null) {
if(prev.next.data == key) {
return prev;
}
prev = prev.next;
}
return null;
}
public void remove(int key) {
if(this.head.data == key) {
this.head = this.head.next;
return;
}
Node prev = findPrev(key);
if(prev == null) {
System.out.println("链表中没有这个节点");
return;
}
Node del = prev.next;
prev.next = del.next;
}
//删除第一次出现关键字为key的节点方法二
public void remove1(int key) {
Node node = this.head;
if(this.head.data == key) {
this.head = this.head.next;
return;
}
while(node.next.data != key) {
node = node.next;
if(node.next == null) {
System.out.println("链表中没有这个节点");
return;
}
}
node.next = node.next.next;
}
//删除所有值为key的节点,只需要遍历一次
public void removeAllKey(int key) {
Node prev = this.head;
Node cur = this.head.next;
while(cur != null) {
if (cur.data == key) {
prev.next = cur.next;
} else {
prev = prev.next;
}
cur = cur.next;
}
//判断头节点是否为关键字
if(this.head.data == key) {
this.head = this.head.next;
}
}
//得到单链表的长度
public int size() {
int count = 0;
Node cur = this.head;
while(cur != null) {
cur = cur.next;
count++;
}
return count;
}
//打印单链表
public void display() {
Node cur = this.head;
if(this.head == null) {
System.out.println("没有存放数据");
}
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
public void clear() {
this.head = null;
}
}