题目描述:
解题思路:
- [1, 2, 3, 4, 5, 6] n = 6 k = 1
- 倒数第一个,是正数的第六个
- 倒数第k个,是正数的第n - k + 1个
代码实现:
#include <iostream>
using namespace std;
struct ListNode {
ListNode* next;
int data;
};
bool FindReverseKthInLinkedList(ListNode* head, int k) {
auto p = head;
int n = 0;
while (p->next) {
n++;
p = p->next;
}
int cnt = n - k + 1;
auto q = head->next;
while (--cnt && q) {
q = q->next;
}
if (!q) {
return false;
}
cout << q->data << endl;
return true;
}
void Print(ListNode* root) {
if (!root) {
return;
}
auto p = root->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
ListNode a, b, c, d, e, f;
a.data = 10;
b.data = 20;
c.data = 30;
d.data = 40;
e.data = 50;
f.data = 60;
ListNode root;
root.next = &a;
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = &f;
f.next = nullptr;
Print(&root);
FindReverseKthInLinkedList(&root, 1);
FindReverseKthInLinkedList(&root, 2);
FindReverseKthInLinkedList(&root, 3);
FindReverseKthInLinkedList(&root, 4);
FindReverseKthInLinkedList(&root, 5);
FindReverseKthInLinkedList(&root, 6);
return 0;
}