题目:如果链表的结点总数为奇数,则返回中间结点;如果结点的总数为偶数,则返回中间结点的任意一个。
程序代码:
#include <iostream>
struct ListNode
{
int iData;
ListNode *pNext;
};
void PrintList(ListNode* pHead)
{
while (pHead)
{
std::cout << pHead->iData << " ";
pHead = pHead->pNext;
}
std::cout << std::endl;
}
void CreateList(ListNode *&pHead, int *arr, int len)
{
pHead = (ListNode*)malloc(sizeof(ListNode));
if(arr == NULL || len <= 0)
{
pHead = NULL;
return;
}
ListNode *pNext = pHead;
ListNode *tmp;
for (int i = 0; i < len; i++)
{
tmp = (ListNode*)malloc(sizeof(ListNode));
tmp->iData = arr[i];
pNext->pNext = tmp;
pNext = pNext->pNext;
}
pHead = pHead->pNext;
pNext->pNext = NULL;
}
ListNode* FindMidNode(ListNode* pHead)
{
ListNode*pFirst, *pSecond;
pFirst = pSecond = pHead;
while (pSecond)
{
pSecond = pSecond->pNext;
if (pSecond)
{
pSecond = pSecond->pNext;
pFirst = pFirst->pNext;
}
}
return pFirst;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
ListNode *pHead, *pNode;
CreateList(pHead, arr, 9);
PrintList(pHead);
pNode = FindMidNode(pHead);
std::cout << pNode->iData << std::endl;
system("pause");
return 0;
}