Sword refers to offer - input a linked list, output the k-th node from the bottom of the linked list

Q; input a linked list, output the k-th node from the bottom of the linked list.

A: Define two pointers:
  (1) The first pointer traverses forward k-1 from the head pointer of the linked list, and the second pointer remains unchanged;
  (2) Starting from the kth step, the second pointer also Start traversing from the head pointer of the linked list;

  (3) Since the distance between the two pointers is kept at k-1, when the first (going in front) pointer reaches the end of the linked list, the second (going in the back) pointer is exactly the k-th penultimate a node.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325965386&siteId=291194637