Remove Duplicates from Sorted List(LeetCode)

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

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

给你一个链表,移除值重复的结点。

思路:

从头遍历,遇到val相同的就删除。

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
	ListNode* deleteDuplicates(ListNode* head) {
		if (head == NULL)
			return NULL;
		ListNode *p = head;
		while (p->next)
		{
			if (p->val == p->next->val)
			{
				p->next = p->next->next;
			}
			else
			{
				p = p->next;
			}
			
		}
		return head;
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/81978464