PTA-7-19 求链式线性表的倒数第K项

题目:https://pintia.cn/problem-sets/15/problems/826

输入格式:输入一个数n,即要求倒数第n个数。然后输入线性表中的数,终止的标志为输入的数为负数;

思路:

定义两个指针,让第一个指针先走k步,然后两个指针一起移动,第一个指针移到末尾的时候,第二个指针就到了倒数第K个位置,输出第二个指针的值。

#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 1000

typedef struct List{
    struct List *next;
    int data;
}List,*PList;
int main(){
     int temp;
     int k,cnt=0;
     PList L;
     L = new List;
     List *s=L,*r=L,*p;
     scanf("%d",&k);
     int f=k;
     while(1){
      scanf("%d",&temp);
       if(temp<0)   break;
             p=new List;
             p->data = temp;
            r->next = p;
             r = p;
             k--;
            cnt++;
            if(k<1)
                s= s->next;
     }
     if( f>cnt)
         printf("NULL");
     else printf("%d",s->data);

 }

猜你喜欢

转载自blog.csdn.net/qq_39681830/article/details/81235327