编码实现环状单向链表(尾指针直接指向头指针,中间没有空节点),去除连续的重复元素的操作。
比如: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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 13:28:08