题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

快慢指针实现

#include<iostream>
using namespace std;
struct ListNode{
    int m_nKey;
    ListNode* m_pNext;
    ListNode(int val): m_nKey(val), m_pNext(nullptr){

    }
};
int getVal(ListNode* dummy, int len);
int main(){
    int n = 0;
    while(cin >> n){
        int val = 0;
        int len = 0;
        ListNode* dummy = new ListNode(0);
        ListNode* cur = dummy;
        for(int i = 0; i < n; ++i){
            cin >> val;
            cur->m_pNext = new ListNode(val);
            cur = cur->m_pNext;
        }
        cin >> len;
        if(len <= 0 || len > n)
            cout << 0 << endl;
        else
            cout << getVal(dummy, len) << endl;

        cur = dummy;
        while(cur != nullptr){
            ListNode* temp = cur->m_pNext;
            delete cur;
            cur = temp;
        }
        dummy = nullptr;
        cur = nullptr;
    }
    return 0;
}

int getVal(ListNode* dummy, int len){
    if(dummy->m_pNext == nullptr)
        return 0;
    ListNode* fast = dummy;
    ListNode* slow = dummy->m_pNext;
    while(len){
        fast = fast->m_pNext;
        len--;
    }
    while(fast->m_pNext != nullptr){
        slow = slow->m_pNext;
        fast = fast->m_pNext;
    }
    return slow->m_nKey;
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务