链表中倒数第k个节点

来源:互联网 发布:入骨相思知不知微盘 编辑:程序博客网 时间:2024/06/06 01:30

题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路:1、第一遍循环得到链表长度,第二遍循环找到倒数第k个元素

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {        int len = 0;        if (pListHead == NULL) return NULL;        ListNode* temp = pListHead;        while (temp->next != NULL) {            len++;            temp = temp->next;        }        len = len - k + 1;        if (len < 0) return NULL;        temp = pListHead;        while (len != 0) {            temp = temp->next;            len--;        }        return temp;    }};

2、定义两个指针都指向头节点,其中一个先往后移动k-1个位置,然后两个指针一起移动,当其中一个到达链表尾时,另一个指向的元素即为倒数第k个元素。

/*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 *first, *second;        first = pListHead, second = pListHead;        int len = k - 1;        while (len != 0) {            if(second->next != NULL)                second = second->next;            else return NULL;            len--;        }        while (second->next != NULL) {            second = second->next;            first = first->next;        }        return first;    }};