链表中倒数第k个结点

链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

思想(没想出来:(): 一次遍历同时找出倒数第k个, 利用两个指针变量, 其中一个先走k-1步后, 第二个指针变量开始游走, 直至第一个指针走完整个数组, 此时第二个指针变量指向倒数第k个元素

版本一来自牛客网, 版本二参考书上思路编的

版本一: 返回方式太霸道了, return i < k ? NULL : q;把i<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) {
        ListNode *p, *q;
        p = q = pListHead;
        int i = 0;

        for (; p != NULL; i++) {
            if (i >= k)
                q = q->next;
            p = p->next;
        }
        return i < k ? NULL : q;
    }
};

版本二: 牛客提交报错, vs中的测试通过, 可能测试不全

/*
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 ((NULL == pListHead) || (NULL == pListHead->next) || (0 == k)) {
		return NULL;
	}
    
    ListNode *fcurrent = pListHead->next;
	ListNode *scurrent = pListHead->next;

	for (decltype(k) i = 0; i < k - 1; i++) {
		fcurrent = fcurrent->next;
	}

	while (NULL != fcurrent->next) {
		scurrent = scurrent->next;
		fcurrent = fcurrent->next;
	}

	return scurrent;
}
};

版本二的测试程序:

#include <iostream>

using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {
	}
};

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
	ListNode *fcurrent = pListHead->next;
	ListNode *scurrent = pListHead->next;

	if ((NULL == pListHead) || (NULL == pListHead->next) || (0 == k)) {
		return NULL;
	}

	for (decltype(k) i = 0; i < k - 1; i++) {
		fcurrent = fcurrent->next;
	}

	while (NULL != fcurrent->next) {
		scurrent = scurrent->next;
		fcurrent = fcurrent->next;
	}

	return scurrent;
}

int main(void) {
	ListNode head(0), n1(1), n2(2), n3(3), n4(4), n5(5);
	ListNode *temp = NULL;
	head.next = &n1;
	n1.next = &n2;
	n2.next = &n3;
	n3.next = &n4;
	n4.next = &n5;

	temp = FindKthToTail(&head, 5);
	cout << temp->val << endl;
}

if ((NULL == pListHead) || (NULL == pListHead->next) || (0 == k)) {
	return NULL;
}

ListNode *fcurrent = pListHead->next;
ListNode *scurrent = pListHead->next;

for (int i = 0; (NULL != fcurrent->next); i++) {
	if (i >= k - 1) {
		scurrent = scurrent->next;
	}
	fcurrent = fcurrent->next;
}
return scurrent;
posted @ 2019-02-26 12:50  张飘扬  阅读(365)  评论(0编辑  收藏  举报