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

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

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//注意链表的定义语句 
//next处要用struct ListNode*因为ListNode方法还没有定义
//链表的写入 head tail  used三个指针;
typedef struct ListNode
{
  int m_nKey;
  struct ListNode* m_pNext;
}ListNode;

int main()
{
  int n;
  while (scanf("%d", &n) != EOF)
  {
    ListNode *num, *head,*tail;
    head = (ListNode *)malloc(sizeof(ListNode));
    head->m_pNext =NULL;

    tail = head;
    for (int i = 0; i < n; i++)
    {
      num = (ListNode *)malloc(sizeof(ListNode));
      scanf("%d", &num->m_nKey);
      num->m_pNext = NULL;
      
      tail->m_pNext = num;
      tail = num;
    }
    head = head->m_pNext;

    int search;
    scanf("%d", &search);
    if (search <= 0 || search > n)
    {
      printf("0\n");
    }
    else
    {
      ListNode *find;
      find = head;
      for (int i = 0; i < n - search; i++)
      {
        find = find->m_pNext;
      }
      printf("%d\n",find->m_nKey);
    }
  }

  return 0;
}

全部评论
题目限定,构建后要忘掉链表长度,后半部分应该不能使用n吧。
3 回复 分享
发布于 2022-05-07 18:03

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
6 2 评论
分享
牛客网
牛客企业服务