given a single link list (l0, l1, l2, l3,,,ln), and transform it to (l0, ln, l1, ln-2, l2, ln-3)

一道微软的编程题,趁午休的时间做了一下,如果有不对之处,希望指出。

#include<string>
#include<iostream>
using namespace std;

typedef struct LNode {
	char m_nValue;
	struct LNode* p_mNext;
}LNode;

LNode* createList(char* pStr) {
	int strLen = strlen(pStr);
	LNode* pHead = NULL;
	LNode* pNode, *pTemp;
	for (int i = 0; i < strLen; i++) {
		pNode = (LNode*)malloc(sizeof(LNode));
		pNode->m_nValue = pStr[i];
		pNode->p_mNext = NULL;
		if (NULL == pHead) {
			pHead = pNode;
		} else {
			pTemp->p_mNext = pNode;
		}
		pTemp = pNode;
	}
	return pHead;
}

LNode* reverseList(LNode* pHead) {
	if (NULL == pHead || NULL == pHead->p_mNext)
		return pHead; 
	LNode* pNewHead = NULL;
	LNode* pNode;
	while (pHead) {
		pNode = pHead;
		pHead = pHead->p_mNext;
		pNode->p_mNext = pNewHead;
		pNewHead = pNode;
	}
	return pNewHead;
}

LNode* reorderList(LNode* pHead) {
	if (NULL == pHead || NULL == pHead->p_mNext || NULL == pHead->p_mNext->p_mNext)
		return pHead;
	LNode* pSlow = pHead;
	LNode* pFast = pHead;
	while (pFast->p_mNext && pFast->p_mNext->p_mNext) {
		pSlow = pSlow->p_mNext;
		pFast = pFast->p_mNext->p_mNext;
	}
	LNode* pFirst = pHead;
	LNode* pSecond = pSlow->p_mNext;
	pSlow->p_mNext = NULL;
	pSecond = reverseList(pSecond);
	LNode *pFirstNext, *pSecondNext;
	while (pSecond) {
		pFirstNext = pFirst->p_mNext;
		pSecondNext = pSecond->p_mNext;
		pFirst->p_mNext = pSecond;
		pSecond->p_mNext = pFirstNext;
		pFirst = pFirstNext;
		pSecond = pSecondNext;
	}
	return pHead;
}

void printList(LNode* pHead) {
	LNode* pNode = pHead;
	while (pNode) {
		cout << pNode->m_nValue << " ";
		pNode = pNode->p_mNext;
	}
	cout << endl;
}

int main(int argc, char* argv[]) {
	char str[] = "abcdefghi";
	LNode* pHead = createList(str);
	pHead = reorderList(pHead);
	printList(pHead);
	cin.get();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值