8.链表中倒数第k个节点
题目内容:
代码及思路:
#include<iostream>
#include<vector>
using namespace std;
struct Linklist
{
int val;
Linklist* next;
};
class solution
{
public:
Linklist* buildlist()
{
int num;
Linklist* p1 = nullptr;
Linklist* p2 = nullptr;
Linklist* head = nullptr;
char ch;
do
{
cin >> num;
p1 = new Linklist;
p1->val = num;
if (head == nullptr)
head = p1;
else
p2->next = p1;
p2 = p1;
cin.get(ch);
} while (ch == ',');
if (head == nullptr)
return nullptr;
p2->next = nullptr;
return head;
}
//使用两个指针,first指针先走k步,然后紧接着second指针前进,当second走到倒数第k个节点位置时,first指针走到最后一个节点位置
Linklist* Findkthtotail(Linklist* head,int k)
{
if (head == nullptr||k==0)
return nullptr;
Linklist* first = head;
Linklist* second = nullptr;
//first前进k步
for (int i = 0; i < k - 1; i++)
{
//要判断k步与链表长度的关系
if (first->next != nullptr)
first = first->next;
else
return nullptr;
}
second = head;
while (first ->next!= nullptr) //first走到最后一个节点时,second刚好位于倒数第k个节点上
{
first = first->next;
second = second->next;
}
return second;
}
};
void main()
{
solution* object = new solution();
Linklist* head=object->buildlist();
Linklist* res = object->Findkthtotail(head,2);
cout << res->val << endl;
}