/**
* 带头节点的单链表的实现
*
* @param <T>
*/
//指向单链表的第一个节点
private HeadEntry<T> head;
public Link() {
this.head = new HeadEntry<>(0, null, null);
}
/**
* 单链表的头插法
*
* @param val
*/
public void insertHead(T val) {
Entry<T> node = new Entry<>(val, this.head.next);
this.head.next = node;
this.head.cnt += 1; // 更新头节点中链表节点的个数
}
/**
* 单链表的尾插法
*
* @param val
*/
public void insertTail(T val) {
Entry<T> node = head;
while (node.next != null) {
node = node.next;
}
node.next = new Entry<>(val, null);
}
/**
* 单链表中删除值尾val的节点
*
* @param val
*/
public void remove(T val) {
Entry<T> pre = head;
Entry<T> cur = head.next;
while (cur != null) {
if (cur.data == val) {
// val节点的删除
pre.next = cur.next;
// 只删除第一个值为val的节点
cur = pre.next; // 删除链表中所有值为val的节点
} else {
pre = cur;
cur = cur.next;
}
}
}
/**
* 打印单链表的所有元素的值
*/
public void show() {
Entry<T> temp = this.head.next;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
/**
* 单链表的节点类型
*
* @param <T>
*/
private static class Entry<T> {
T data; // 链表节点的数据域
Entry<T> next; // 下一个节点的引用
public Entry(T data, Entry<T> next) {
this.data = data;
this.next = next;
}
}
/**
* 头节点的类型
*
* @param <T>
*/
private static class HeadEntry<T> extends Entry<T> {
int cnt; // 用来记录节点的个数
public HeadEntry(int cnt, T data, Entry<T> next) {
super(data, next);
this.cnt = cnt;
}
}
/**
* 逆置单链表
*/
public void reverse(T val) {
if (this.head.next == null) {
return;
}
Entry<T> cur = this.head.next.next;
this.head.next.next = null;
Entry<T> post = null;
while (cur != null) {
cur.next = head.next;
head.next = cur;
cur = post;
}
}
/**
* 获取倒数第K个单链表节点的值
* 1.遍历一次链表,统计链表节点的个数length
* 2.length-k
* 只遍历一次链表,就找出来呢?
* cur1指向第一个 cur2 指向正数第k个
*/
public T getLastK(int k) {
Entry<T> cur1 = this.head.next;
Entry<T> cur2 = this.head;
//cur1指向第一个节点,cur2指向正数第k个节点
for (int i = 0; i < k; i++) {
cur2 = cur2.next;
if (cur2 == null) {
return null;
}
}
//当cur2到达末尾的时候,cur1指向的就是倒数第k个节点
while (cur2.next != null) {
cur1 = cur1.next;
cur2 = cur2.next;
}
return cur1.data;
}
/**
* 判断链表是否有环
* 快慢指针 初始化 都指向第一个节点
* 慢指针一次向后走一个节点
* 快指针一次向后走两个节点
*/
/**
* 判断链表是否有环,如果有,返回入环节点的值,没有环,返回null
*
* @return
*/
public T getLinkCircleVal() {
Entry<T> slow = this.head.next;
Entry<T> fast = this.head.next;
// 使用快慢指针解决该问题
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (fast == null) {
return null;
} else {
// fast从第一个节点开始走,slow从快慢指针相交的地方开始走,它们相遇的时候,就是环的入口节点
fast = this.head.next;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow.data;
}
}
}