给出一个n个元素的链表输出倒数第k个节点

用两个指针;初始化为头指针;用其中一个指针遍历链表,当该指针遍历到第k个节点时,另外一个指针开始从头节点开始遍历链表;两个指针之间的距离为k;遍历完链表时第二个指针所指向的节点就是倒数第K个:

#include<cstdio>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node{
    int val;
    node *next;
    node(){
        next=NULL;
        }
};
#define Fin freopen("/home/kapop/pro/1.txt","r",stdin);
#define Fout freopen("/home/kapop/pro/2.txt","w",stdout);
int main(){
   /* Fin
    Fout*/
    int n;
    int k,x;
    while(cin>>n>>k){
   node *head=NULL,*p=NULL,*T=NULL;
   p=head=new node;
    T=head;
        int cnt=0;
     for(int i=0;i < n; i++){
          cin>>x;
           p -> val=x;
           p -> next=new node;
           cnt++;
           p=p->next;
           if(k < cnt)
            {
              T=T->next;
            }
         } 
         cout<<"res: ";
         cout<<T->val<<endl;}
    return 0;
}

/*
10 3
1 2 3 4 5 6 7 8 9 10
11 5
1 2 3 4 5 6 7 8 9 10 11
12 5
1 2 3 4 5 6 7 8 9 10 11 12


res: 8
res: 7
res: 8

*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值