分别实现两个函数,一个可以删除单链表中倒数第K个节点,另一个可以删除双链表中倒数第K个节点。
public static Node removeLastKthNode(Node head, int lastKth){
if (head == null || lastKth < 1){
return head;
}
Node cur = head;
// 第一遍移动
while(cur != null){
lastKth --;
cur = cur.next;
}
// K大于链表的长度,直接返回
if (lastKth > 0){
return head;
}
// 删除的是头结点--倒数最后一个-第一个
if (lastKth == 0){
return head.next;
}
// 一般情况
if (lastKth < 0){
cur = head; // 重置当前链表
while(++lastKth != 0){ // 找到的是前一个节点 ++lastKth:这个操作很秀
cur = cur.next; // 向下移动
}
cur.next = cur.next.next; // 找到要删除的节点
}
return head;
}
// 与单链表不同的是需要对last指针进行重置
public DoubleNode removeLastKthNode(DoubleNode head, int lastKth){
if (head == null || lastKth < 1){
return head;
}
DoubleNode cur = head;
while(cur != null){
lastKth --;
cur = cur.next;
}
if (lastKth == 0){
head = head.next;
head.last = null; // 区别1
return head;
}
if (lastKth > 0){
return head;
}
if (lastKth < 0){
cur = head;
while(++ lastKth != 0){
cur = cur.next;
}
cur.next = cur.next.next;
if (cur.next.next != null)
cur.next.next.last = cur;
}
return head;
}
参考书目:
《程序员代码面试指南 IT名企算法与数据结构题目最优解》