83. Remove Duplicates from Sorted List

时间:2021-02-28 04:46:06

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


 class Solution {
 public:
	 ListNode* deleteDuplicates(ListNode* head) {
		 ListNode * p = head; 
		 if (p == NULL || p->next == NULL) return head;
		 ListNode  *q;
		
		 while (p->next != NULL)
		 {
			 q = p->next; 
			 if (p->val != q->val)  p = q;  
			 else
			 {
				 while (q->next != NULL  &&   q->val == q->next->val)
				 {
					 q = q->next;
				 }
				 p->next = q->next; 
				 p = q;
			 }
		 }

		 return head;
	 }
 };