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

链表中倒数第k个结点

时间:2019-07-04 14:32:41      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:The   null   sub   输出   end   ini   ext   scribe   倒数   

题目描述

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

思路

设置两个指针 fast 、slow,fast先走k-1步,然后再一起走;
先走的k-1步中,如果遇到fast=nullptr,说明链表长度小于k-1,就没有倒数第k项,那就直接返回空指针;
当fast走到最后一个结点,slow恰好在倒数第k个结点。
 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6             val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
12         if(!pListHead || k<=0) return nullptr;
13         ListNode* fast = pListHead;
14         ListNode* slow = pListHead;
15         for(int i=0;i<k-1;i++){
16             fast = fast->next;
17             if(!fast) return nullptr;
18         }
19         while(fast->next){
20             fast = fast->next;
21             slow = slow->next;
22         }
23         return slow;
24     }
25 };

 

pyhton

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def FindKthToTail(self, head, k):
 9         # write code here
10         res = []
11         while head:
12             res.append(head)
13             head = head.next
14         if k<1 or k>len(res):
15             return
16         return res[-k]

 

链表中倒数第k个结点

标签:The   null   sub   输出   end   ini   ext   scribe   倒数   

原文地址:https://www.cnblogs.com/pacino12134/p/11132029.html

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