/**
* 单链表的节点类型
* @param <T>
*/
static class Entry<T>{
T data; // 链表节点的数据域
Entry<T> next; // 下一个节点的引用
public Entry(T data, Entry<T> next) {
this.data = data;
this.next = next;
}
}
/**
* 头节点的类型
* @param <T>
*/
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(){
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){
post = cur.next;
cur.next = head.next;
head.next = cur;
cur = post;
}
}
/**
* 获取倒数第K个单链表节点的值
* 1.遍历一次链表,统计链表节点的个数length
* 2.length - 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;
}
单链表的逆置、获取倒数第k个单链表节点的值的方法实现
最新推荐文章于 2020-07-19 00:46:47 发布