题目描述
输入一个链表,输出该链表中倒数第k个结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
}
};
通过代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//#include <iostream>
//#include <vector>
using namespace std;
class Solution {
public:
ListNode* FindKthToTail(ListNode* p, unsigned int k) {
auto p1=p;//定义一个自动变量
// 注意代码的鲁棒性
if(p==NULL||k==0)
return NULL;
//有两个指向同一个链表的指针
//让p1运行k次
for(int i=0;i!=k;++i)
{
if(!p1)return nullptr; //nullptr,是c++中空指针类型的关键字
else
p1=p1->next;
}
//p1 和p 执行剩下的n-k次,此时相当于p的输出就是倒数k次的值
while(p1)
{
p1=p1->next;
p=p->next;
}
return p;
}
};
关于auto的用法:
参考:http://www.cnblogs.com/KunLunSu/p/7861330.html
C++11 auto
auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,类似的关键字还有decltype。举个例子:
int a = 10;
auto au_a = a;//自动类型推断,au_a为int类型
cout << typeid(au_a).name() << endl;
typeid运算符可以输出变量的类型。程序的运行结果输出了
int
这种用法就类似于C#中的var关键字。auto的自动类型推断发生在编译期,所以使用auto并不会造成程序运行时效率的降低。而是否会造成编译期的时间消耗,我认为是不会的,在未使用auto时,编译器也需要得知右操作数的类型,再与左操作数的类型进行比较,检查是否可以发生相应的转化,是否需要进行隐式类型转换。
参考:
【1】https://www.nowcoder.com/profile/3630596/codeBookDetail?submissionId=16898019