学习完链表之后,需要进行大量练习,从而熟能生巧。首先,我们建立一个基础链表,后续练习都建立在此基础上:
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class MyLinkedList {
public Node head;//保存单链表的头节点的引用
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;
}
public void disPlay() {
Node cur = this.head;
while (cur != null) {
System.out.println(cur.data + " ");
cur = cur.next;
}
System.out.println();
}
//查找是否包含关键字key是否在单链表中
public boolean contains(int key) {
Node cur = this.head;
while (cur != null) {
if (cur.data == key) {
return true;
}
cur = cur.next;
}
return false;
}
//得到单链表长度
public int size() {
int count = 0;
Node cur = this.head;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
}
- 删除链表中等于给定值 val 的所有节点。
public void removeAllVal(int val) {
Node prev = this.head;
Node cur = this.head.next; //代表要删除的节点
while (cur != null) {
if (cur.data == val) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur