链表和顺序表不同,顺序表的每个元素是存在数组里面的,而链表的每个元素都是一个对象,完成单链表的增删改查等操作是需要了解面向对象的含义的,但是写单链表的目的主要也是提高面向对象的这种思维方式。
创建一个Node类,然后可以再main方法里头new出节点对象来,这个对象包含两个信息,一个是data,另外一个是Node 型的next,这个next之所以是Node是因为链表是通过节点与节点相连的,一个node的前驱和后继都是节点或者是空。
class Node { public int data; public Node next; public Node() { } public Node(int data) { this.data = data; } public Node head; }
头插法把元素插入链表
//头插法 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; }
//得到单链表的长度public int size() { int cnt = 0; Node cur = this.head; while (cur != null) { cur = cur.next; cnt++; } return cnt; }
//任意位置插入,第一个数据节点为0号下标public void addIndex(int index, int data) { Node node = new Node(data); Node cur = this.head; if (index < 1 || index > size()) { throw new RuntimeException("不在范围内"); } else { if (index == 1) { addFirst(data); } else if (index == size()) { addLast(data); } else { while (index - 1 > 1) { cur = cur.next; index--; } node.next = cur.next; cur.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的节点public void remove(int key) { if (this.head == null) { throw new RuntimeException("链表为空"); } else { if (contains(key)) { if (this.head.next == null) { if (this.head.data == key) { this.head = null; } return; } if (this.head.data == key) { this.head = this.head.next; } Node cur = this.head.next; Node pre = this.head; while (cur != null) { if (cur.data == key) { pre.next = cur.next; return; } pre = pre.next; cur = cur.next; } } } }
//删除所有值为key的节点
public void removeAllKey(int key) {
Node pre = this.head;
Node cur = pre.next;
if (contains(key)) {
if (this.head.data == key) {
this.head = this.head.next;
}
while (cur != null) {
if (cur.data == key) {
cur = cur.next;
pre.next = cur;
} else {
pre = pre.next;
cur = cur.next;
}
}
} else {
System.out.println("不存在该值");
}
}
//打印链表public void display() { Node cur = this.head; while (cur != null) { System.out.print(cur.data); cur = cur.next; } System.out.println(); }
//清空链表
public void clear() {
this.head = null;
}
要完成单链表的增删改查用这些代码块就行了。