求链表中倒数第k个节点
注意鲁棒性和算法效率的典型例题:(头文件省略)
typedef struct node { int data; struct node* next; }ListNode; ListNode* FindKthToTail(ListNode* pListHead, unsigned int k); int main() { int i; const int N = 50; ListNode *head, *p; //随机数种子 srand((unsigned int)time(0)); //生成链表 head = p = new ListNode; head->data = rand() % 101; head->next = nullptr; for ( i = 0; i < N; i++) { p = p->next = new ListNode; p->data = rand() % 101; p->next = nullptr; } //输出链表 for (p = head; p; p = p->next) { cout << " " << p->data; } cout << endl; //产生随机数 i = rand() % 101; cout << "随机数n=" << i << endl; //输出倒数第k个数 p = FindKthToTail(head, 3); if (nullptr == p) { cout << "find error" << endl; } else { cout << "find result: " << p->data << endl; } cin.get(); return 0; } ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if (nullptr == pListHead || !k) return nullptr; int i; ListNode *p, *q; p = q = pListHead; for ( i = 0; i < k-1; i++) { if (nullptr==p->next) { return nullptr; } else { p = p->next; } } while (nullptr != p->next) { p = p->next; q = q->next; } return q; }