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

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

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

#include<stdio.h>
struct ListNode
{
    int  key;
    struct ListNode *next;
};
void returnback(struct ListNode *head,int k){
    struct ListNode *p;
    int i=1;
    p=head->next;
    while(p)
    {
        p=p->next;
        if(i>=k)
        {
            head=head->next;
        }
        i++;
    }
    if(k>i||k==0)
        printf("%d\n",NULL);
    else
        printf("%d\n",head->key);
}
int main(){
    int n,val,k;
    while(scanf("%d",&n)!=EOF)
    {
        struct ListNode *p=(struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode *head=(struct ListNode*)malloc(sizeof(struct ListNode));
        p->next=NULL;
        head=p;
        for(int i=0;i<n;i++)
        {
            struct ListNode *q=(struct ListNode*)malloc(sizeof(struct ListNode));
            q->next=NULL;
            scanf("%d",&val);
            q->key=val;
            p->next=q;
            p=q;
        }
        scanf("%d",&k);
        returnback(head,k);
    }
    return 0;
}
全部评论

相关推荐

菜鸡29号:根据已有信息能初步得出以下几点: 1、硕士排了大本和大专 2、要求会多语言要么是招人很挑剔要么就是干的活杂 3、给出校招薪资范围过于巨大,说明里面的薪资制度(包括涨薪)可能有大坑
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务