不计算单链表长度,找到链表倒数第K个元素。
#include <iostream>
using namespace std;
struct Node
{
int number;
Node *next;
};
Node *input()
{
Node *head = NULL, *tail = NULL;
int x;
cin >> x;
while (x != -1)
{
Node *p = new Node;
p->number = x;
p->next = NULL;
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = p;
}
cin >> x;
}
return head;
}
Node *findlastk(Node *head, int k)
{
Node *s = head;
Node *t = head;
for (int i = 0; i < k; i++)
{
if (t)
t = t->next;
else
return NULL;
}
while (t != NULL)
{
s = s->next;
t = t->next;
}
return s;
}
int main()
{
Node *head = input();
if (head)
{
int k;
cin >> k;
Node *lastk = findlastk(head, k);
if (lastk)
cout << lastk->number << endl;
}
return 0;
}