删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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;
	}
}

二、优化

   还可以使用加头节点或递归的方法来解决

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值