Google筆試題 --- 環狀鏈表去重

來源:互聯網
上載者:User

標籤:Google校招筆試題

編碼實現環狀單向鏈表(尾指標直接指向頭指標,中間沒有空節點),去除連續的重複元素的操作。

比如:1(頭)->2->2->3->3->1->1(頭) 去除以後的結果是1->2->3,注意頭尾的1也要去掉一個。


//時間複雜度為O(N)//空間複雜度為O(1)//代碼如下:#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <climits>#include <cmath>#include <queue>#include <cassert>#include <algorithm>#define MAXN 10010#define RST(N)memset(N, 0, sizeof(N))using namespace std;typedef int data_t;typedef struct ListNode{    data_t data;    struct ListNode *next;}LNode, *pNode;pNode Create(int n, int *hashTable){    pNode head = NULL;    pNode p1 = NULL, p2 = NULL;    p1 = p2 = (pNode)malloc(sizeof(LNode));    while(n--)    {        cin >> p1->data;        hashTable[p1->data]++;   //統計        if(head == NULL)            head = p1;        else            p2->next = p1;        p2 = p1;        p1 = (pNode)malloc(sizeof(LNode));    }    p2->next = head;    //指向頭    return head;}void uniqueListNode(pNode head, int *hashTable){    assert(head != NULL);    pNode pre = head;    pNode cur = head->next;    while(cur != head && cur != NULL)   //去重    {        pNode p = cur;        pNode Next = cur->next;        if(hashTable[cur->data] == 1)            pre = cur;        else if(hashTable[cur->data] > 1)        {            hashTable[cur->data]--;            pre->next = Next;            free(p);    //釋放        }        cur = Next;    }}int main(){    int n;    while(cin >> n)    {        int hashTable[MAXN] = {0};   //hash儲存出現的次數        pNode head = Create(n, hashTable);    //構造一個環狀單鏈表        uniqueListNode(head, hashTable);   //去重        /***** result *****/        cout << head->data << "->";        for(pNode p=head->next; p!=head; p=p->next)        {            cout << p->data;            if(p->next != head) cout << "->";            else cout << endl;        }    }    return 0;}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Google筆試題 --- 環狀鏈表去重

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.