构建链表不多讲了,找到链表倒数第k个节点,需要先定义两个指针,fast 和slow,让fast先走k步,然后慢指针也开始走,直到最后fast走到NULL,slow指向的就是倒数第k个节点。

#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode
{
    int m_nKey;
    struct ListNode* m_pNext;
}ListNode;

int main()
{
    int count = 0;
    while(scanf("%d",&count)!=EOF)
    {
            ListNode* end = NULL;
            ListNode* head = NULL;
            int n = 0;
            int k = 0;
            while(count--)//构建链表
        {
            scanf("%d",&n);
            ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
            newnode->m_nKey = n;
            newnode->m_pNext = NULL;
            if(end==NULL && head == NULL)
            {
                head = newnode;
                end = newnode;
            }
            else
            {
                end->m_pNext = newnode;
                end = newnode;
            }
        }
        scanf("%d",&k);
        ListNode* fast = head;
        ListNode* slow = head;
        while(k--)
        {
            fast = fast->m_pNext;
        }
        while(fast!=NULL)
        {
            fast = fast->m_pNext;
            slow = slow->m_pNext;
        }
        printf("%d\n",slow->m_nKey);
        //释放动态开辟内存防止内存泄露哦
        ListNode* next = NULL;
        while(head!=NULL)
        {
            next = head->m_pNext;
            free(head);
            head = next;
        }
    }
    
    return 0;
}