题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

构建链表不多讲了,找到链表倒数第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;
}
全部评论
链表长度不足7返回空没考虑
点赞 回复 分享
发布于 2022-07-17 21:39

相关推荐

评论
12
2
分享
牛客网
牛客企业服务