链表概念
链表是一种物理存储单元上非连续的存储结构。
接口实现
以 非循环,不带头结点的单链表为例
1. 抽象链表类
class ListNode {
public int val;//值
public ListNode next;//存储下一个节点的地址 也就是说 这个是一个引用
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
}
1. 头插法
- 定义标识整个链表的头部head
- 把data封装成节点类型
- 新节点的next域连上head
- 修改head
- 头插法创建的链表,打印出来的顺序与创建的顺序相反
public void addFirst(int data) {
public ListNode head;//标识整个链表的头
ListNode node = new ListNode(data);
// 无需区分是否是第一次插入
// 1. 修改Noode.next
node.next = this.head;
// 2. 修改head
this.head = node;
}
2. 尾插法
- 定义标识整个链表的头部head
- 考虑初始空链表的情况
- 用cur来遍历链表找到最后一个节点
- cur指向的最后一个节点的next域连上新节点
- 尾插法创建的链表,打印出来的顺序与创建的顺序相同
public void addLast(int data) {
ListNode node = new ListNode(data);
ListNode cur = this.head;
// 0. 空链表 ,即第一次插入的情况
if(this.head == null){
this.head = node;
return;
}
// 1. 找尾节点
while(cur.next != null){
cur = cur.next; //此时cur指向尾节点
}
// 2. 修改next
cur.next = node;
}
3. 求单链表长度
注意:不能用head去遍历链表,因为我们需要head来只想第一个节点作为标识,故可以用一个head的副本cur来遍历
public int size(){
int count = 0;
ListNode cur = head;
while(cur != null){
count++;
cur = cur.next;
}
return count;
}
4. 任意位置插入节点
- 判断插入位置是否合法转化成头插或尾插的情况
- 考虑特殊index下变成头插或尾插的情况
- findIndexSubOne()函数找到插入位置的前一个节点cur
- 新节点的next域连上原链表中cur的下一个节点
- cur指向的前一个节点的next域连上新节点 (3,4步的顺序错误会导致断链)
public void addIndex(int index,int data) {
ListNode node = new ListNode(data);
// 1. 判断index是否合法
if(index < 0 || index > size()){
System.out.println("index不合法\n");
return;
}
// 2. 判断Index = 0 头插法
if(index == 0){
addFirst(data);
return;
}
// 3. 判断Index = size() 尾插法
if(index == size()){
addLast(data);
return;
}
//4. 找到插入位置的前一个节点的地址 ,cur 走 index - 1 步
ListNode cur = findIndexSubOne(index); //此时cur指向index - 1 节点
node.next = cur.next;
cur.next = node;
}
public ListNode findIndexSubOne(int index){
ListNode cur = this.head;
int count = 0;
for (; count == index -1; count++) {
cur = cur.next;
}
return cur;
}
5. 查找是否包含关键字key是否在单链表当中
public boolean contains(int key) {
ListNode cur = this.head;
while(cur != null){
if(cur.val == key){
return true;
}
cur = cur.next;
}
return false;
}