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

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

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

思路:
1、创建带头结点且头结点为空的单链表
2、通过“头插法”输入数据
3、循环获取链表长度。根据长度和倒数第几个节点K算出要输出的节点

#include <stdio.h>

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

static struct ListNode* creatNode()
{
    struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
    if(!head)
    {
        return NULL;
    }
    head->m_pNext = NULL;
    return head;
}

static int printf_node(struct ListNode *head)
{
    struct ListNode *p = head->m_pNext;
    int len_node = 0;
    while(p != NULL)
    {
        printf("%d ", p->m_nKey);
        p = p->m_pNext;
        len_node++;
    }
    printf("\n");
    //printf("len_node = [%d]\n", len_node);
    return 0;
}

/* 尾插法 */
static int add_end(struct ListNode* head, int data)
{
    struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
    if(!new)
    {
        return -1;
    }
    new->m_nKey = data;
    new->m_pNext = NULL;
    struct ListNode *p = head;
    while(p->m_pNext != NULL)
    {
        p = p->m_pNext;
    }
    p->m_pNext = new;
    return 0;
}

/* 头插法 */
static int add_beg(struct ListNode* head, int data)
{
    struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
    if(!new)
    {
        return -1;
    }
    new->m_nKey = data;
    new->m_pNext = head->m_pNext;
    head->m_pNext = new;
    return 0;
}

static int printf_index(struct ListNode *head, int end_index)
{
    struct ListNode *p = head->m_pNext;
    int len_node = 0;
    while(p != NULL)
    {
        p = p->m_pNext;
        len_node++;
    }
    //printf("len_node = [%d]\n", len_node);
    p = head;
    for(int i = 0; i < len_node-end_index+1; i++)
    {
        p = p->m_pNext;
    }
    printf("%d\n", p->m_nKey);
    return 0;
}

int main()
{
    int num = 0;
    while(scanf("%d", &num) != EOF)
    {
        if(num >= 1 && num <= 1000)
        {
            struct ListNode* head = creatNode();
            int data = 0;
            for(int i = 0; i < num; i++)
            {
                scanf("%d", &data);
                add_end(head, data);
            }
            //printf_node(head);
            int k = 0;
            scanf("%d", &k);
            printf_index(head, k);
        }
    }
    return 0;
}
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务