given a single link list (l0, l1, l2, l3,,,ln), and transform it to (l0, ln, l1, ln-2, l2, ln-3)
2013-11-08 13:57
495 查看
一道微软的编程题,趁午休的时间做了一下,如果有不对之处,希望指出。
#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; }
相关文章推荐
- 给定单链表L:L0→L1→...→Ln-1→Ln, 重新排序:L0→Ln→L1→Ln-1→L2→Ln-2→...
- python: how to delete a given item if it exist in the list
- Q.2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only acce
- 给定一个链表,比如L1--->L2---->L3---->................----->Ln,把链表调整为L1---->Ln----->L2----->Ln-1------>L3----
- 机器学习中的范数规则化L0、L1与L2范数
- L0范式,L1范式,L2范式的简单理解
- L0,L1,L2
- l0-Norm, l1-Norm, l2-Norm, … , l-infinity Norm
- 读“机器学习中的范数规则化之(一)L0、L1与L2范数”笔记
- L0/L1/L2/Lp/L∞范数的联系与区别
- PHP Warning: strftime(): It is not safe to rely on the system's timezone testlink
- 机器学习中的范数规则化之L0、L1与L2范数、核范数
- ln: failed to create symbolic link 'libavutil.so': Operation not supported
- 机器学习中的范数规则化之(一)L0、L1与L2范数
- L0范式,L1范式,L2范式的简单理解
- L0、L1、L2、Elastic Net正则项
- l0-Norm, l1-Norm, l2-Norm, … , l-infinity Norm
- L0 norm、L1 norm、L2 norm(L0、L1、L2范数)
- 机器学习中的范数规则化之(一)L0、L1与L2范数
- 1006. insert for single link list with head node