当前位置:
首页 >
面试题 02.02. 返回倒数第 k 个节点
发布时间:2025/3/15
43
豆豆
生活随笔
收集整理的这篇文章主要介绍了
面试题 02.02. 返回倒数第 k 个节点
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
2020-03-20
1.题目描述
返回倒数第 k 个节点2.题解
首先将链表逆序,然后求出第k个即可3.代码
#include <iostream> using namespace std;// Definition for singly-linked list. struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {} };class Solution { public:int kthToLast(ListNode* head, int k) {ListNode* p=head,*q=p->next,*t;p->next=NULL;while (q){t=q->next;q->next=p;p=q;q=t;}int cnt=1,res;while (p){if (cnt==k){res=p->val;break;}p=p->next;cnt++;}return res;} };int main(){Solution s;ListNode* head=NULL, *p,*q;int i;p=(ListNode*)malloc(sizeof(ListNode));p->val=1;p->next=NULL;head=p;q=p;p=(ListNode*)malloc(sizeof(ListNode));p->val=0;q->next=p;p->next=NULL;q=p;p=(ListNode*)malloc(sizeof(ListNode));p->val=1;q->next=p;p->next=NULL;cout<<s.kthToLast(head,3)<<endl;return 0; }总结
以上是生活随笔为你收集整理的面试题 02.02. 返回倒数第 k 个节点的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 网站自动登录功能的设计
- 下一篇: YUV格式学习:YUV420P、YV12