数据结构和算法经典100题-第13题

本文介绍了一种高效查找单向链表中倒数第K个节点的方法,并提供了具体的实现代码。通过定义两个指针并控制它们之间的距离为K,当先驱指针到达链表尾部时,另一个指针即指向目标节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
输入一个单向链表,输出该链表中倒数第k个结点,
链表的倒数第1个结点为链表的尾指针。


题目分析:
题目分析:此题目不难,只需要定义两个链表的结点指针,分别指向头结点。
然后其中一个向前移动k-1步,然后这两个结点分别向后移动。一直到
前面的的指针移动到链表的尾指针位置。


我们看一下代码,头文件:

//
//  13th.h
//  100-alg-tests
//
//  Created by bobkentt on 15-5-9.
//  Copyright (c) 2015年 kedong. All rights reserved.
//

#ifndef ___00_alg_tests___3th__
#define ___00_alg_tests___3th__

#include <stdio.h>

struct Node
{
    int value;
    Node* next;
};

class List {
    Node* m_head;
    Node* m_tail;

public:
    Node* insert(int value);

    /*
     * @param <k> <链表的倒数第几个元素>
     * return <Node> <返回链表的倒数第k个结点地址>
     */
    Node* find(int k);

    List(int* arrary,int size);
    ~List() { };

};

int test_13();

#endif /* defined(___00_alg_tests___3th__) */

源码实现:

List::List(int* arrary,int size) {
    for (int i = 0; i < size; i++) {
        if (NULL == insert(arrary[i]))
            return ;
    }
}


Node* List::insert(int value) {
    if (NULL == m_head) {
        m_head = (Node*)malloc(sizeof(Node));
        if (NULL == m_head) {
            cout<<strerror(errno)<<endl;
        }

        m_head->value = value;
        m_head->next = NULL;

        m_tail = m_head;

        return m_head;
    }

    if (NULL != m_tail) {
        m_tail->next = (Node*)malloc(sizeof(Node));
        if (NULL == m_tail->next) {
            cout<<strerror(errno)<<endl;
        }
        m_tail = m_tail->next;
        m_tail->value = value;
        m_tail->next = NULL;
        return m_tail;

    }

    cout<<"Insert error "<<endl;
    return NULL;

}


Node* List::find(int k) {
    if (NULL == m_head) {
        return NULL;
    }

    Node* front = m_head;
    Node* behind = front;

    for (int i = 0; i < k - 1; i++) {
        if (NULL == front->next) {
            return NULL;
        }
        front = front->next;
    }

    for (int i = 0; ; i++) {
        if (NULL == front->next) {
            break;
        }
        front = front->next;
        behind = behind->next;
    }

    return behind;
}

测试程序:

int test_13() {
#define ARRAY_LEN 100

    int array[ARRAY_LEN];

    for (int i = 0; i < ARRAY_LEN; i++) {
        array[i] = i + 1;
    }

    List obj(array,ARRAY_LEN);
    Node* element = obj.find(5);

    cout<<element->value<<endl;

    return 0;
}

我们看一下打印输出:

96
Program ended with exit code: 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值