链表:删除链表中倒数第K个节点

问题:实现一个函数,可以删除链表中倒数第K个节点。

要求时间复杂度为 O(N),额外空间复杂度为 O(1)。

分析:让链表从头开始走到尾,每移一步,就让 K 值减一,当链表走到结尾时,如果 K 值大于0,说明不用调整链表,因为链表根本没有倒数第 K 个节点,此时将原链表返回即可;如果 K 值等于0,说明链表倒数第 K 个节点就是头结点,此时返回 head.next,即第二个节点作为头结点即可。

如果 K 小于0时,则进行以下操作:

1. 重新从头结点开始走,每移一步,就让 K 的值加1;

2. 当 K 等于0时,移动停止,移动到的结点就是要删除节点的前一个节点;

下面就链表为单链表和双链表两种情况,给出代码

 1 //单链表
 2 public class Node
 3 {
 4     public int value;
 5     public Node next;
 6 
 7     public Node(int value)
 8     {
 9         this.vaule = value;
10     }
11 }
12 
13 public node removeLastKthNode(Node head, int LastKth)
14 {
15     if(head == null || Kth < 1)
16         return head;
17 
18     Node cur = head;
19 
20     while(cur != null)
21     {
22         cur = cur.next;
23         LastKth--;
24     }
25 
26     if(LastKth == 0)
27     {
28         head = head.next;
29     }
30     else if(LastKth < 0)
31     {
32         cur = head;
33         while(++LastKth != 0)
34         {
35             cur = cur.next;
36         }
37         cur.next = cur.next.next;
38     }
39     return head;
40 }
//双链表
public class DoubleNode
{
    public int value;
    public DoubleNode next;
    public DoubleNode pre;

    public DoubleNode(int value)
    {
        this.vaule = value;
    }
}

public node removeLastKthNode(DoubleNode head, int LastKth)
{
    if(head == null || Kth < 1)
        return head;

    DoubleNode cur = head;

    while(cur != null)
    {
        cur = cur.next;
        LastKth--;
    }

    if(LastKth == 0)
    {
        head = head.next;
        head.pre = null;
    }
    else if(LastKth < 0)
    {
        cur = head;
        while(++LastKth != 0)
        {
            cur = cur.next;
        }
        Double newNext = cur.next.next;
        cur.next = newNext;
        if(newNext != null)
            newNext.pre = null;
    }
    return head;
}

参考资料:程序员代码面试指南 IT名企算法与数据结构题目最优解,左程云

原文地址:https://www.cnblogs.com/2015110615L/p/6659778.html