码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer 15:链表的倒数第k个节点

时间:2019-09-30 23:17:33      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:解题思路   int   c++   desc   content   offer   null   剑指offer   turn   

题目描述

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

解题思路

使用快慢指针法,让快指针先走k步,然后再让慢指针开始走,当快指针到达链表尾部时,慢指针刚好到达倒数第k个节点。

C++代码实现:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
    
if(pListHead==NULL){ return NULL; } ListNode *p1,*p2; p1=pListHead; int count=0; int pos=k; while(pos>0 && p1!=NULL){ p1=p1->next; pos--; count++; } //如果链表长度不到K,输入不合法,返回NULL if(count!=k){ return NULL; } p2=pListHead; while(p1!=NULL){ p1=p1->next; p2=p2->next; } return p2; } };

剑指offer 15:链表的倒数第k个节点

标签:解题思路   int   c++   desc   content   offer   null   剑指offer   turn   

原文地址:https://www.cnblogs.com/fancy-li/p/11614388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!