Sword Finger Offer Interview Question 22.リンクリストの最後から2番目のk番目のノード[simple] -double pointer

私の解決策:

ダブルポインターを使用して、最初にヘッドノードをヘッドを指すように設定します

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        ListNode* a=new ListNode(-1);
        a->next=head;
        ListNode* i=a;
        ListNode* j=a;
        int count=0;
        while(j){
            if(count<k){
                j=j->next;
                count++;
            }
            else{
                j=j->next;
                i=i->next;
            }
        }
        return i;
    }
};

 

オリジナルの記事を65件公開 いいね1 訪問数488

おすすめ

転載: blog.csdn.net/qq_41041762/article/details/105462985