题目网址
头插法建立的链表,求倒数第k个就是求第k个。
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//这是一种指向结点的类型
typedef struct LNode *List;
typedef struct LNode
{
int data;
List next;
};
int c;
int n = 0;
int main()
{
int t,a;
List head = (List)malloc(sizeof(List));
head->next = NULL;
cin >> a;
while (scanf("%d",&t) && t>=0)
{
List s = (List)malloc(sizeof(List));
s->data = t;
//头插法建立链表
s->next = head->next;
head->next = s;
n++;
}
List p = head;
if(a<0||a==0||a>n)
{
cout << "NULL";
return 0;
}
while (a--)
{
c = p->next->data;
p = p->next;
}
cout << c;
return 0;
}