题目:输入一个链表,输出该链表中倒数第K个结点。链表的尾结点是倒数第1个节点。
思路:两个指针相差k-1。
#include <iostream>
using namespace std;
struct ListNode {
int m_nValue;
ListNode *m_pNext;
};
ListNode *CreateList() {
int a;
cin >> a;
ListNode *head;
head = NULL;
if (a != -1) {
head = new ListNode;
head->m_nValue = a;
head->m_pNext = CreateList();
}
return head;
}
ListNode *FindKthToTail(ListNode *phead, int k) {
if (phead == NULL || k == 0) {
cout << "Invalid Input!" << endl;
return NULL;
}
ListNode *pFirst = phead;
ListNode *pSecond = phead;
for (int i = 1; i < k; i++) {
if (pFirst->m_pNext != NULL)
pFirst = pFirst->m_pNext;
else {
cout << "Invalid k!" << endl;
return NULL;
}
}
while (pFirst->m_pNext != NULL) {
pFirst = pFirst->m_pNext;
pSecond = pSecond->m_pNext;
}
cout << pSecond->m_nValue << endl;
return pSecond;
}
int main() {
int k = 1;
ListNode *head = CreateList();
ListNode *Kth = FindKthToTail(head, k);
(Kth == NULL) ? cout << "Invalid!" << endl : cout << Kth->m_nValue << endl;
return 0;
}