標籤: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筆試題 --- 環狀鏈表去重