C++基础知识(六)链表等

  • 求链表中倒数第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* p=pListHead;
        ListNode* q=pListHead;
        while(k-->0){
            p=p->next;
            if(p==NULL && k==0) return pListHead; //链表长度等于k
            if(p==NULL)return NULL; //链表长度小于k
        }
        while(p!=NULL){
            p=p->next;
            q=q->next;
        }
        return q;
        
        /*
        if(pListHead==NULL)return NULL;
        int count=0;
        ListNode* p=pListHead;
        while(p!=NULL){
            p=p->next;
            count++;
        }
        if(k>count)return NULL;
        else{
            p=pListHead;
            int i=0;
            while(i < count-k){
                p=p->next;
                i++;
            }
            return p;
        }
        */
        
    }
};

  

猜你喜欢

转载自www.cnblogs.com/chuckle/p/9019382.html