Wins the Offer-14. Penultimate k linked list nodes (C ++ / Java)

topic:

Input a linked list, the linked list output reciprocal k-th node.

analysis:

The first solution, we can first traverse the list again, calculate the total number of nodes in n, then the head node nk check nodes, i.e., k is the penultimate node.

The second solution, is the use of double pointer, both pointers are pointing to the first node, the first pointer advances to the k-1 nodes, then proceeds with the two hands, when the pointer reaches the end of a first node, a second pointer finger nodes is our requirements.

Also to be noted that when k is 0 to return null, and if k is larger than the number of nodes in the linked list, should return null.

program:

C++

/*
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 == nullptr || k == 0)
            return nullptr;
        ListNode* pFirst = pListHead;
        ListNode* pSecond = pListHead;
        for(int i = 0; i < k-1; ++i){
            if(pFirst->next != nullptr)
                pFirst = pFirst->next;
            else
                return nullptr;
        }
        while(pFirst->next != nullptr){
            pFirst = pFirst->next;
            pSecond = pSecond->next;
        }
        return pSecond;
    }
};

Java

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k == 0)
            return null;
        ListNode pFirst = head;
        ListNode pSecond = head;
        
        for(int i = 0; i < k-1; ++i){
            if(pFirst.next != null)
                pFirst = pFirst.next;
            else
                return null;
        }
        while(pFirst.next != null){
            pFirst = pFirst.next;
            pSecond = pSecond.next;
        }
        return pSecond;
    }
}

Guess you like

Origin www.cnblogs.com/silentteller/p/11879142.html