【面试题】返回链表倒数第K个节点

题目描述:

输入一个链表,返回链表倒数第K个节点。

实现过程:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

#define DataType int

typedef struct Node
{
    DataType data;
    struct Node* _pNext;
}*pNode;

pNode InitNode(pNode pHead)
{
    pHead = NULL;
    return pHead;
}


pNode BuyNewNode(DataType data)
{
    pNode pNewNode = NULL;
    pNewNode = (pNode)malloc(sizeof(pNode));
    if (pNewNode)
    {
        pNewNode->data = data;
        pNewNode->_pNext = NULL;
    }
    return pNewNode;
}

void InstallFrontNode(pNode *pHead, DataType data)
{
    assert(pHead);
    pNode temp = NULL;

    if (*pHead == NULL)
        *pHead = BuyNewNode(data);

    else
    {
        temp = BuyNewNode(data);
        temp->_pNext = *pHead;
        *pHead = temp;
    }

}

void PrintList(pNode pHead)
{
    assert(pHead);

    while (pHead)
    {
        printf("%d -> ", pHead->data);
        pHead = pHead->_pNext;
    }
    printf("NULL");
    printf("\n");
}

pNode FindKToTailList(pNode pHead, unsigned int key)
{
    assert(pHead);

    unsigned int i = 0;
    pNode pTempHead = pHead;
    pNode pTempBegin = NULL;

    if (pHead == NULL || key == 0)
        return NULL;

    else
    {
        for (i = 0; i < key - 1; ++i)
        {
            if (pTempHead->_pNext != NULL)
            {
                pTempHead = pTempHead->_pNext;
            }
            else
            {
                return NULL;
            }
        }

        pTempBegin = pHead;
        while (pTempBegin->_pNext != NULL)
        {
            pTempHead = pTempHead->_pNext;
            pTempBegin = pTempBegin->_pNext;

        }
        return pTempBegin;
    }
}

void test()
{
    pNode pHead1 = NULL;
    pNode Knum = NULL;


    InstallFrontNode(&pHead1, 4);
    InstallFrontNode(&pHead1, 6);
    InstallFrontNode(&pHead1, 0);
    InstallFrontNode(&pHead1, 7);
    InstallFrontNode(&pHead1, 4);
    InstallFrontNode(&pHead1, 3);


    PrintList(pHead1);

    Knum = FindKToTailList(pHead1, 3);
    printf("%d\n", Knum->data);
}


int main()
{
    test();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

askunix_hjh

谢谢请我吃糖~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值