链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};

class Solution
{
public:
ListNode* FindKthToTail(ListNode* pListHead,unsigned int k)
{
ListNode* p=pListHead;
for(int i=0;i<k;i++) //先让p走k-1个节点,剩下的就是总长-K+1个节点
{
if(!p)
return NULL;
else
p=p->next;

}
//pListNode和p一起走,当p走完剩下的总长-k=+1个节点时,pListNode也走了总长-k+1个节点,刚好走到倒数第k个节点
while(p)
{
p=p->next;
pListHead=pListHead->next;
}

return pListHead;
}
};

int main()
{
Solution s;
int n;
struct ListNode *head = NULL,*p = NULL,*key = NULL,*x=NULL;
scanf("%d",&n);
head=(struct ListNode*)malloc(sizeof(struct ListNode));
p=(struct ListNode*)malloc(sizeof(struct ListNode));
head->next=p;
for(int i=0;i<n;i++)
{
scanf("%d",&p->val);
p->next=(struct ListNode*)malloc(sizeof(struct ListNode));
x=p;
p=p->next;
}
x ->next=NULL; //最后一个节点指向空
p=head->next;
/*
for(int i=0;i<n;i++)
{
printf("%d",p->val);
p=p->next;
}
*/
key = s.FindKthToTail(p,3);
cout<<key->val<<endl;
}

原文地址:https://www.cnblogs.com/dshn/p/8798539.html