zoukankan      html  css  js  c++  java
  • 剑指offer--面试题15

    题目:打印单向链表中倒数第k个节点

    以下为自己所写代码,未经过验证,只是写个思路。。。

    #include<iostream>
    #include<vector>
    #include<exception>
    
    using namespace std;
    //节点定义
    struct ListNode
    {
        int m_nValue;
        ListNode* m_pNext;
    };
    
    void FindKthToTail(ListNode* pHead, unsigned int k)
    {
        if(pHead == NULL)
            throw new std::exception("Invalid parameters!");
    
        std::vector<int> Values;
        ListNode* pNode = pHead;
    
        while(pNode != NULL)
        {
            Values.push_back(pNode->m_nValue);
            pNode = pNode->m_pNext;
        }
    
        if(k > Values.size())
            throw new std::exception("Invalid parameters!");
        else
            std::cout<<Values[Values.size() - k]<<std::endl;    
    
    }

    如果不允许使用vector,则另想办法:用具有某种限制的两个指针进行一次遍历即可!

    自己所写代码如下:

    ListNode* FindKthToTail(ListNode* pHead, unsigned int k)
    {
        if(pHead == NULL || k <= 0)
            return NULL;
        int index = 1;
        ListNode* pNode = pHead;
        while(i <= k && pNode != NULL)
            pNode = pNode->m_pNext;
        if(pNode == NULL)
            return NULL;
        else
        {
            ListNode* pNodeFollow = pHead;
            while(pNode->m_pNext != NULL)
            {
                pNode = pNode->m_pNext;
                pNodeFollow = pNodeFollow->m_pNext;
            }
        }
    
        return pNodeFollow;
    
    }

    错误处理后,均return NULL;

    让防御性编程成为自己的习惯!

    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    C语言-if语句
    C语言-表达式
    C语言-基础
    Java for LeetCode 187 Repeated DNA Sequences
    Java for LeetCode 179 Largest Number
    Java for LeetCode 174 Dungeon Game
    Java for LeetCode 173 Binary Search Tree Iterator
    Java for LeetCode 172 Factorial Trailing Zeroes
    Java for LeetCode 171 Excel Sheet Column Number
    Java for LeetCode 169 Majority Element
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3252374.html
Copyright © 2011-2022 走看看