问题:
在单链表中删除倒数第K个节点
说明:
●让链表从头开始走到尾,每移动一步,就让 K 值减 1,当链表走到结尾时,如果K值大于0,说明不用调整链表,
因为链表根本没有倒数第K个节点,此时将原链表直接返回即可;
●如果 K 值等于 0,说明链表倒数第 K 个节点就是头节点,此时直接返回head.next,也就是原链表的第二个节点,让第二个节点作为链表的头返回即可,相当于删除头节点;
●如果K值小于0,
1.重新从头节点开始走,每移动一步,就让K的值加1。
2.当K等于0时,移动停止,移动到的节点就是要删除节点的前一个节点。
这样做是非常好理解的,因为如果链表长度为N,要删除倒数第K个节点,很明显,倒数第K个节点的前一个节点就是第N-K个节点。在第一次遍历后,
K的值变为K-N。第二次遍历时,K的值不断加1,加到0就停止遍历,第二次遍历当然会停到第N-K个节点的位置。
public static void main(String[] args)
{
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.next = node2;
node2.next = node3;
Node node = removeLastKthNode(node1, 1);
System.out.println(node.value);
}
private static Node removeLastKthNode(Node head, int lastKth)
{
if(head == null || lastKth < 1) return null;
Node cur = head;
while(cur != null)
{
cur = cur.next;
lastKth --;
}
if(lastKth == 0) return head;
if(lastKth < 0)
{
cur = head;
while (++lastKth !=0)
{
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}