题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
好吧一看就觉得是使用两次遍历,(或许一次遍历也可以做,只是判断复杂一些)
第一次遍历,查找重复节点,第二次遍历更改链表指针指向,删除节点
代码实现如下:
#pragma once
#include <vector>
namespace delete_repeat_list
{
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(nullptr) {
}
};
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == nullptr) return nullptr;
auto tmp = pHead;
int value = tmp->val;
int index = 0;
std::vector<int> _vec;
while (tmp != nullptr)
{
if (tmp->val != value)
{
value = tmp->val;
for (int i = 0; i < index; i++)
{
_vec.push_back(index);
}
index = 0;
}
tmp = tmp->next;
index++;
}
for (int i = 0; i < index; i++)
{
_vec.push_back(index);
}
ListNode* pRet = nullptr;
ListNode* pTmp = nullptr;
for (int i = 0; i < _vec.size(); i++)
{
if (_vec[i] == 1 && pRet == nullptr)
{
pRet = pHead;
pTmp = pHead;
}
else if(_vec[i] == 1)
{
pTmp->next = pHead;
pTmp = pTmp->next;
}
pHead = pHead->next;
}
if (pTmp != nullptr)
pTmp->next = nullptr;
return pRet;
}
};
}
test.cpp
#pragma once
#include "delete_repeat_list.h"
namespace delete_repeat_list
{
void start_test()
{
Solution s;
ListNode* p1 = new ListNode(1);
ListNode* p2 = new ListNode(2);
ListNode* p3 = new ListNode(3);
ListNode* p4 = new ListNode(3);
ListNode* p5 = new ListNode(4);
ListNode* p6 = new ListNode(4);
ListNode* p7 = new ListNode(5);
p1->next = p2;
p2->next = p3;
p3->next = p4;
p4->next = p5;
p5->next = p6;
p6->next = p7;
p7->next = nullptr;
auto ret = s.deleteDuplication(p1);
int c;
}
}
二、优化
还可以使用加头节点或递归的方法来解决