美团网2014年校园招聘笔试题(哈工大)

2014年美团网校园招聘研发类笔试
1、一堆硬币,一个机器人,如果是反的就翻正,如果是正的就抛掷一次,无穷多次后,求正反的比例

设正比例为x,反的比例就是1-x;现在根据反的翻正,正的重新投掷,那么正的就为1-x+(1/2*x),反的就为1/2*x.无穷次会达到平衡,那么1-x就应该等于1/2*x。所以x为2/3,即正的为2/3


4、链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6,用程序实现

#include <iostream>
using namespace std;

struct ListNode
{
	int m_nValue;
	ListNode *m_pNext;
};

ListNode* CreateList(int val)
{
	ListNode *pHead = new ListNode;

	pHead->m_nValue = val;
	pHead->m_pNext = NULL;

	return pHead;
}

void InsertNode(ListNode **pHead, int val)
{
	ListNode *pNode = new ListNode;
	pNode->m_nValue = val;
	pNode->m_pNext = NULL;

	while ((*pHead)->m_pNext != NULL)
	{
		(*pHead) = (*pHead)->m_pNext;
	}

	(*pHead)->m_pNext = pNode;
	(*pHead) = pNode;
}

void PrintList(ListNode *pHead)
{
	while (pHead != NULL)
	{
		cout<<pHead->m_nValue<<" ";
		pHead = pHead->m_pNext;
	}
	cout<<endl;
}

ListNode* Reverse(ListNode *pHead)
{
	if (pHead == NULL || pHead->m_pNext == NULL)
	{
		return pHead;
	}

	ListNode *pPre = NULL;
	ListNode *pCurrent = pHead;
	ListNode *pPost = pHead->m_pNext;

	while (pCurrent->m_pNext != NULL)
	{
		pCurrent->m_pNext = pPre;
		pPre = pCurrent;
		pCurrent = pPost;
		pPost = pPost->m_pNext;
	}
	pCurrent->m_pNext = pPre;

	return pCurrent;
}



ListNode* ReverseList(ListNode *pHead, int k)
{
	if (pHead==NULL || pHead->m_pNext==NULL)
	{
		return pHead;
	}

	ListNode *pPre = NULL;
	ListNode *pCurrent = pHead;
	ListNode *pPost = pHead->m_pNext;
	ListNode *pStart = NULL;
	ListNode *pEnd = NULL;

	int n = 0;
	pEnd = pCurrent;
	pEnd->m_pNext = NULL;
	while (pPost != NULL)
	{
		++n;
		if (n == (k+1))
		{
			pStart = pPre;
			pEnd->m_pNext = ReverseList(pCurrent, k);

			return pStart;
		}
		else
		{
			pCurrent->m_pNext = pPre;
			pPre = pCurrent;
			pCurrent = pPost;
			pPost = pPost->m_pNext;
		}
	}

	pCurrent->m_pNext = pPre;
	pStart = Reverse(pCurrent);
	return pStart;
}

int main()
{
	ListNode *pHead = NULL;
	ListNode *head = NULL;
	int n;
	cout<<"输入链表中节点的个数 n:"<<endl;
	cin>>n;
	cout<<"请输入n个整数值:"<<endl;
	for (int i=0; i<n; ++i)
	{
		int data;
		cin>>data;

		if (pHead == NULL)
		{
			pHead = CreateList(data);
			head = pHead;
		}
		else
		{
			InsertNode(&pHead, data);
		}
	}

	int k;
	cout<<"请输入k:"<<endl;
	cin>>k;
	head = ReverseList(head, k);
	PrintList(head);

	system("pause");
	return 0;
}


你可能感兴趣的:(美团网2014年校园招聘笔试题(哈工大))