zoukankan      html  css  js  c++  java
  • 剑指22 链表倒数第k个节点

    输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 k = 2.

    返回链表 4->5.

    双指针,两个指针保持k的距离。

    注意要思考可能会导致程序出错的情况,如k=0,head为空指针,或k超过了链表的长度。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* getKthFromEnd(ListNode* head, int k) {
    12         if(head==nullptr || !k)
    13             return nullptr;
    14         ListNode *frontptr, *backptr;
    15         frontptr=head;
    16         int count=1;
    17         while(frontptr!=nullptr && count!=k){
    18             count++;
    19             frontptr=frontptr->next;
    20         }
    21         if(count!=k)
    22             throw "the len of List is less than k";
    23         backptr=head;
    24         while(frontptr->next!=nullptr){
    25             frontptr=frontptr->next;
    26             backptr=backptr->next;
    27         }
    28         return backptr;
    29     }
    30 };
  • 相关阅读:
    repr() Vs str()
    默认参数
    元组
    字典
    电脑可以办的两类最基本的事情
    代码块
    变量名
    print的逻辑
    input的逻辑
    让python2听懂中文
  • 原文地址:https://www.cnblogs.com/rookiez/p/13233144.html
Copyright © 2011-2022 走看看