面试题:删除链表中重复的节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sea_muxixi/article/details/82702706

题意:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

循环:


class Solution {
public:
	ListNode* deleteDuplication(ListNode* pHead)
	{
		ListNode* first = new ListNode(-1);
		first->next = pHead;

		ListNode* last = first;

		ListNode* now = pHead;

		while (now != NULL && now->next != NULL)
		{
			if (now->val == now->next->val)
			{
				int val = now->val;
				while (now!=NULL && now->val == val)
					now = now->next;
				last->next = now;
			}
			else
			{
				last = now;
				now = now->next;
			}
		}
		return first->next;
	}
};

递归:

class Solution {
public:
	ListNode* deleteDuplication(ListNode* pHead)
	{
		if (pHead == NULL) return NULL;
		if (pHead->next == NULL) return pHead;

		ListNode* current = NULL;

		if (pHead->val == pHead->next->val)
		{
			current = pHead->next->next;
			while (current != NULL && current->val == pHead->val)
				current = current->next;
			return deleteDuplication(current);
		}
		else
		{
			current = pHead->next;
			pHead->next = deleteDuplication(current);
			return pHead;
		}
	}
};

猜你喜欢

转载自blog.csdn.net/Sea_muxixi/article/details/82702706