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

2014-11-24 01:44:11 · 作者: · 浏览: 1
一道微软的 编程题,趁午休的时间做了一下,如果有不对之处,希望指出。
#include  
#include  
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; }