删除单链表的倒数第k个结点

策略

直接遍历总数为len,再次遍历第len-k+1个就是答案,但是这样遍历了O(N+k)个,可以在O在更短的时间内找到

图示

删除单链表的倒数第k个结点

参考代码

删除单链表的倒数第k个结点
#include <iostream>
using namespace std;

typedef struct ListNode
{
    int value;
    ListNode* next;
}ListNode;

void createList(ListNode *&head)
{
    head = new(ListNode);
    head->value = 1;
    head->next = NULL;

    ListNode *p2 = new(ListNode);
    p2->value = 2;
    p2->next = NULL;
    head->next = p2;

    ListNode *p3 = new(ListNode);
    p3->value = 3;
    p3->next = NULL;
    p2->next = p3;

    ListNode *p4 = new(ListNode);
    p4->value = 4;
    p4->next = NULL;
    p3->next = p4;
}
void deleteList(ListNode *p)
{
    ListNode *next = NULL;
    while(p != NULL)
    {
        next = p->next;
        delete p;
        p = NULL;
        p = next;
    }
}



bool deleteKNode_2(ListNode *head, int k)
{
    if(head == NULL || k <= 0)
        return false;
    ListNode *pre = head;
    for(int i = 0; i < k - 1; ++i)
    {
        if(pre == NULL)
            return false;
        pre = pre->next;
    }
    ListNode *cur = head;
    while(pre->next)
    {
        pre = pre->next;
        cur = cur->next;
    }
    cout << cur->value;
    cout << "succeed:" << endl;
    return true;
}
int main()
{
    ListNode *head = NULL;
    createList(head);
    int k = 8;
    
    cout << "Result:" << deleteKNode_2(head, 2) << endl;
    deleteList(head);
}
删除单链表的倒数第k个结点

结果

删除单链表的倒数第k个结点

三点注意

1. 指针为空

2. k<=0

3. k<len





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3608117.html,如需转载请自行联系原作者

上一篇:Java Json API:Gson使用简单入门


下一篇:单链表问题(反转、是否有环、删除结尾第N个节点、合并两个sortlist、找到交点)