面试题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;
}

posted @ 2020-07-22 21:57  程序员曾奈斯  阅读(121)  评论(0编辑  收藏  举报