class ListNode { public: ListNode() { pNext = NULL; nValue = 0; } ListNode* pNext; int nValue; }; ListNode* CreaList() { int nValue; ListNode* Head = NULL; ListNode* ListIndex = NULL; while(cin >> nValue) { if (Head == NULL) { Head = new ListNode(); Head->nValue = nValue; ListIndex = Head; } else { ListNode* newNode = new ListNode(); newNode->nValue = nValue; ListIndex->pNext = newNode; ListIndex = newNode; } } // cout << "Print List;" << endl; PrintList(Head); return Head; } void PrintList(ListNode* Head) { for (ListNode* pNode = Head; pNode != NULL; pNode = pNode->pNext) { cout << pNode->nValue << " "; } cout << endl; } //运用两个节点 可以达到通过一次遍历完成输出倒数第K个节点 void PrintTheLastK(ListNode* Head, int K) { if (Head == NULL) { cout << "number of list less then " << K << endl; return; } ListNode* firstPoint = Head; ListNode* secondPoint = Head; for (int i = 1; i < K ; i++) { secondPoint = secondPoint->pNext; if (secondPoint == NULL) { cout << "number of list less then " << K << endl; return; } } while(1) { if (secondPoint->pNext == NULL) { cout << "result:" << firstPoint->nValue << endl; return; } firstPoint = firstPoint->pNext; secondPoint = secondPoint->pNext; } }
//拓展 //输入一个单向链表。如果该链表的结点数为奇数,输出中间的结点;如果链表结点数为偶数,输出中间两个结点前面的一个 void PrintMidNode(ListNode* Head) { if (Head == NULL) { return; } ListNode* firstNode = Head; ListNode* secondNode = Head; while (1) { if (secondNode->pNext == NULL || secondNode->pNext->pNext == NULL) { cout << "result:" << firstNode->nValue << endl; return; } secondNode = secondNode->pNext->pNext; firstNode = firstNode->pNext; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-07 08:03:53