首页 > 其他分享 >剑指 Offer22.链表中倒数第k个节点

剑指 Offer22.链表中倒数第k个节点

时间:2023-03-06 18:47:36浏览次数:43  
标签:head slow ListNode temp Offer22 fast next 链表 倒数第

题目描述

 

 

 

解法一

顺序查找

思路:链表长度为n,则链表倒数第k个节点是第n-k个节点

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        int n = 0;
        ListNode *temp = head;
     // for (node = head; node; node = node->next) { n++; } 可替换 while(temp){ n++; temp = temp->next; } for(temp = head; n > k; n--){ temp = temp->next; } return temp; } };

 

解法二

双指针法

思路:fast指针向后走k步,slow与fast同步向后走,

   当fast指针指向链表尾部空节点时,返回slow所指向的节点。

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast && k > 0){
            fast = fast->next;
            k--;
        }
        while(fast){
            fast = fast->next;
            slow = slow->next;
        }
        return slow;       
    }
};

 

标签:head,slow,ListNode,temp,Offer22,fast,next,链表,倒数第
From: https://www.cnblogs.com/zc-030/p/17184613.html

相关文章