赞
踩
#include <iostream> using namespace std; struct ListNode { ListNode* next; int data; }; bool FindReverseKthInLinkedList(ListNode* head, int k) { auto p = head; // 计算链表的长度 不包含头节点,只计算有效的节点 int n = 0; while (p->next) { n++; p = p->next; } int cnt = n - k + 1; auto q = head->next; while (--cnt && q) { q = q->next; } if (!q) { return false; } cout << q->data << endl; return true; } void Print(ListNode* root) { if (!root) { return; } auto p = root->next; while (p) { cout << p->data << " "; p = p->next; } cout << endl; } int main() { // [10, 20, 30, 40, 50, 60] ListNode a, b, c, d, e, f; a.data = 10; b.data = 20; c.data = 30; d.data = 40; e.data = 50; f.data = 60; ListNode root; root.next = &a; a.next = &b; b.next = &c; c.next = &d; d.next = &e; e.next = &f; f.next = nullptr; Print(&root); FindReverseKthInLinkedList(&root, 1); FindReverseKthInLinkedList(&root, 2); FindReverseKthInLinkedList(&root, 3); FindReverseKthInLinkedList(&root, 4); FindReverseKthInLinkedList(&root, 5); FindReverseKthInLinkedList(&root, 6); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。