【牛客】找出单向链表中的一个节点,该节点到尾指针的距离为K

题目链接:https://www.nowcoder.com/practice/0cff324157a24a7a8de3da7934458e34

题目描述

找出单向链表中的一个节点,该节点到尾指针的距离为K。链表的倒数第0个结点为链表的尾指针。要求时间复杂度为O(n)。
链表结点定义如下:
struct ListNode
{
    int m_nKey;
    ListNode* m_pNext;
}
链表节点的值初始化为1,2,3,4,5,6,7。

输入描述:

该节点到尾指针的距离K

输出描述:

返回该单向链表的倒数第K个节点,输出节点的值
示例1

输入

复制
2

输出

复制
6

备注:

请自觉实现一个链表,将1到7依次加入链表,然后再寻找倒数第K个节点。要求加节点与找节点的操作复杂度均为O(n)。
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct ListNode
 4 {
 5     int m_nKey;
 6     struct ListNode *m_pNext;
 7 }*newl;
 8 int main()
 9 {
10     int k;
11     scanf("%d",&k);
12     int i;
13     struct ListNode *newlist=(struct ListNode*)malloc(sizeof(struct ListNode));
14     newlist->m_nKey=1;
15     newlist->m_pNext=NULL;  
16     struct ListNode *head=newlist;
17     for(i=2;i<=7;i++){
18         struct ListNode *tmp=(struct ListNode*)malloc(sizeof(struct ListNode));
19         tmp->m_nKey=i;
20         tmp->m_pNext=NULL;
21         head->m_pNext=tmp;
22         head=tmp;
23     }
24     int cnt=1;
25     head=newlist;
26     while(head){
27         if(cnt==(8-k)){
28             printf("%d\n",head->m_nKey);
29             return 0;
30         }
31         cnt++;
32         head=head->m_pNext;
33     }
34     return 0;
35 }

 

posted @ 2020-04-10 00:39  wydxry  阅读(639)  评论(0编辑  收藏  举报
Live2D