1. 程式人生 > 實用技巧 >面試題18:刪除連結串列中重複的結點

面試題18:刪除連結串列中重複的結點

本題考查連結串列的操作。

C++版本

// 由於可能需要刪除頭結點,所以需要指向頭結點的指標,即二級指標,有兩種方式
// 方式一:引數宣告為二級指標
ListNode** pHead; 
// 方式二:新建指向頭結點的指標
ListNode* vHead = new ListNode(-1);
vHead->next = pHead;
#include <iostream>
#include <algorithm>
using namespace std;

// 定義連結串列
struct ListNode{
    int val;
    struct ListNode* next;
    ListNode(int val):val(val),next(nullptr){}
};

/*
    刪除有序單向連結串列中重複的節點
*/
// 方式一:引數宣告為二級指標
void deleteDuplication(ListNode** pHead){
    if(pHead == nullptr || *pHead == nullptr)
        return ;
    ListNode* pPreNode = nullptr;
    ListNode* pNode = *pHead;
    while(pNode != nullptr){
        ListNode* pNext = pNode->next;
        bool needDelete = false;
        if(pNext != nullptr && pNext->val == pNode->val)
            needDelete = true;
        // 不需要刪除
        if(!needDelete){
            pPreNode = pNode;
            pNode = pNode->next;
        }
        else{
            int value = pNode->val;
            ListNode* pToBeDel = pNode;
            while(pToBeDel != nullptr && pToBeDel->val == value){
                pNext = pToBeDel->next;
                delete pToBeDel;
                pToBeDel = nullptr;
                pToBeDel = pNext;
            }
            if(pPreNode == nullptr)
                *pHead = pNext;
            else
                pPreNode->next = pNext;
            pNode = pNext;
        }
    }
}

// 方式二:新建指向頭結點的指標
ListNode* deleteDuplication(ListNode* pHead)
{
    ListNode *vhead = new ListNode(-1);
    vhead->next = pHead;
    ListNode *pre = vhead, *cur = pHead;
    while (cur) {
        if (cur->next && cur->val == cur->next->val) {
            cur = cur->next;
            while (cur->next && cur->val == cur->next->val) {
                cur = cur->next;
            }
            cur = cur->next;
            pre->next = cur;
        }
        else {
            pre = cur;
            cur = cur->next;
        }
    }
    return vhead->next;
}

int main()
{
    int num[10] = {5,7,4,8,3,2,6,1,9,8};
    for(int i = 0; i < 10; i++)
        cout<<num[i]<<endl;
    return 0;
}