1. 程式人生 > >2014微軟秋季校招演算法筆試題

2014微軟秋季校招演算法筆試題

這道題是來自2014微軟秋季校招筆試題的最後一道演算法筆試題,本部落格提供程式碼解析及程式碼實現!!!

第二部分測試時間為60分鐘,滿分50分。請務必在回答問題前仔細閱讀變成題目。您可以選用C、C++、C#或者Java 其中任何一種程式語言,並且保證您的程式碼可以正確編譯和有正確的結果。另外,請一定要注意您的程式碼的質量。


Given a singly linked list L: (L0 , L1 , L2...Ln-1 , Ln). Write a program to reorder it so that it becomes(L0 , Ln , L1 , Ln-1 , L2 , Ln-2...).

//思路:
L0 -> L1 -> L2 ->.....-> Ln-1 -> Ln
分解為兩個單鏈表:
L0 -> L1 -> L2 ->....-> Ln/2
Ln/2+1 -> ....Ln

反轉第二個單鏈表

然後合併這兩個連結串列

程式碼如下:

//時間複雜度為O(N)
//空間複雜度為O(1)

//程式碼如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <cassert>
#include <climits>
#include <algorithm>
#define MAXN 10010
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;

typedef struct ListNode
{
    int data;
    struct ListNode *next;
}LNode, *pNode;

pNode Create(int n)   //建立一個單鏈表
{
    pNode p1, p2, head;
    head = NULL;
    p1 = p2 = (pNode)malloc(sizeof(LNode));
    int flag = 1;
    while(n--)
    {
        cin >> p1->data;
        if(flag)
        {
            head = p1;
            flag = 0;
        }
        else
            p2->next = p1;
        p2 = p1;
        p1 = (pNode)malloc(sizeof(LNode));
    }
    p2->next = NULL;
    return head;
}

pNode getMidNode(pNode head)   //獲取中間元素指標
{
    assert(head != NULL);
    pNode first = NULL;
    pNode second = NULL;
    first = second = head;
    while(first->next != NULL && first->next->next != NULL)  //這裡注意
    {
        first = first->next->next;
        second = second->next;
    }
    return second;
}

pNode LNReverse(pNode head)   //單鏈表的反轉
{
    assert(head != NULL);
    pNode Cur, Next, Nnext;
    Cur = head;
    Next = Nnext = NULL;
    while(Cur->next != NULL)
    {
        Next = Cur->next;
        Nnext = Next->next;
        Next->next = head;
        Cur->next = Nnext;
        head = Next;
    }
    return head;
}

pNode MergeList(pNode head1, pNode head2)  //合併兩個單鏈表
{
    if(head1 == NULL) return head2;
    if(head2 == NULL) return head1;
    pNode p1 = head1;
    pNode p2 = head2;
    pNode cur1 = NULL;
    pNode cur2 = NULL;

    while(p1!=NULL && p2!=NULL)
    {
        cur1 = p1->next;
        cur2 = p2->next;
        p1->next = p2;
        p2->next = cur1;
        p1 = cur1;
        p2 = cur2;
    }
    return head1;
}

int main()
{
    int n;
    while(cin >> n)
    {
        pNode head = Create(n);  //初始化

        pNode head1 = head;
        pNode pTemp = getMidNode(head);  //獲取中間元素指標
        pNode head2 = pTemp->next;   //截斷
        pTemp->next = NULL;

        head2 = LNReverse(head2);   //反轉
        head = MergeList(head1, head2);    //合併

        for(pNode p=head; p!=NULL; p=p->next)   //結果,測試
        {
            cout << p->data;
            if(p->next != NULL) cout << " ";
            else cout << endl;
        }
    }
    return 0;
}