演算法學習-排序連結串列中去重
阿新 • • 發佈:2019-01-02
題目
給定排序的連結串列,刪除重複元素,只保留重複元素第一次出現的結點。
如:
給定:2->3->3->5->7->8->8->8->9->9-10
返回:2->3->5->7->8->9-10
解析
程式碼如下:若p->next的值和p的值相等,則將p->next->next賦值給p,刪除p->next;重複上述過程,直至連結串列尾端。
// suanfa1.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include <stdlib.h> typedef struct tagSNode { int value; tagSNode* pNext; tagSNode(int v): value(v), pNext(NULL){} }SNode; void Print(SNode* pHead) { if (!pHead) { return; } SNode* p = pHead->pNext; while(p) { printf("%d ", p->value); p = p->pNext; } printf("\n"); } void DeleteDuplicateNode(SNode* pHead) { SNode* pPre = pHead->pNext; SNode* pCur; while (pPre) { pCur = pPre->pNext; if (pCur && (pCur->value == pPre->value)) { pPre->pNext = pCur->pNext; delete pCur; } else { pPre = pCur; } } } void Destory(SNode* pHead) { SNode* next; while (pHead) { next = pHead->pNext; delete pHead; pHead = next; } } int _tmain(int argc, _TCHAR* argv[]) { SNode* pHead = new SNode(0); int data[] = { 2, 3, 3, 5, 7, 8, 8, 8, 9, 9, 30}; int size = sizeof(data) / sizeof(int); for (int i = size - 1; i >= 0; i--) { SNode* p = new SNode(data[i]); p->pNext = pHead->pNext; pHead->pNext = p; } Print(pHead); DeleteDuplicateNode(pHead); Print(pHead); Destory(pHead); system("pause"); return 0; }
還有一個版本去重是將有重複的都刪除掉,不做解釋了,無序的先自己排序然後進行去重