剑指offer 15---查找单链表的倒数第k个节点,要求只能遍历一次链表

来源:互联网 发布:sql学生信息管理系统 编辑:程序博客网 时间:2024/06/01 03:59

查找单链表的倒数第k个节点,要求只能遍历一次链表

#include <iostream>#include <Windows.h>using namespace std;struct ListNode{int _value;ListNode* _next;ListNode(const int& value):_value(value), _next(NULL){}};//查找单链表的倒数第K个结点ListNode* KthList(ListNode* pHead, int k){if (pHead == NULL || k == 0){return NULL;}//快慢指针法ListNode* fast = pHead;ListNode* slow = pHead;for (int i = 0; i < k - 1; ++i){if (fast->_next != NULL){fast = fast->_next;}else{return NULL;}}//此时出了循环fast指向k-1处while (fast->_next != NULL){fast = fast->_next;slow = slow->_next;}return slow;}int main(){//链表为:1 2 3 4 5 6 7 8 9 10ListNode* pHead = new ListNode(1);ListNode* cur = pHead;for (int i = 2; i <= 10; ++i){ListNode* temp = new ListNode(i);cur->_next = temp;cur = temp;}ListNode* tty = KthList(pHead, 6);cout << "单链表的倒数第K个结点:" << "";if (tty != NULL){cout << tty->_value << endl;}system("pause");return 0;}


阅读全文
2 0