查找链表中倒数第k个数

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
/*******************************************************************
 *
 *	函数名称:	MinDelate
 *	函数功能:   /*假设该链表只给出了头指针 head。在不改变链表的前提下,请设计一个尽可能高效的算法,
查找链表中倒数第k(k为正整数个位置上的结点。若查找成功,算法输出该结点的data值,并返回1,否则,只返回0
 * 	函数参数:   LList_t *Head int k
 *  返回结果:   查找成功或否
 * 	注意事项:   None
 * 	函数作者:   1810866453@163.com
 *	创建日期:   2024/04/22
 *	修改历史:
 *	函数版本:	V1.0
 * *****************************************************************/

// 指的是单向链表中的结点有效数据类型,用户可以根据需要进行修改
typedef int DataType_t;

// 构造链表的结点,链表中所有结点的数据类型应该是相同的
typedef struct LinkedList
{
    DataType_t data;         // 结点的数据域
    struct LinkedList *next; // 结点的指针域

} LList_t;

int LList_FindDataPut(LList_t *Head, int k)
{

    LList_t *Phead1 = Head->next;
    LList_t *Phead2 = Head->next;
    int count = 0; // 计数器

    while (Phead1->next)
    {
        Phead1 = Phead1->next; // 遍历到尾的地址
        count++;
    }
    if (k > count)
    {
        return 0;
    }
    for (int i = 0; i < count - k; i++)
    {
        Phead2 = Phead2->next;
    }
    printf("K-th to last data = %d\n", Phead2->data);
    return 1;
}
posted @ 2024-04-22 20:52  Zeratul$$$  阅读(19)  评论(0)    收藏  举报