Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
思路:
用两个指针,一个在前,一个在后,比较两个结点的值,如果相等,后一个指针后移,再比较。
如果不相等,则前一个指针指向后一个指针,然后同时后移。
ListNode* deleteDuplicates(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* p = head, *q = head->next; while (q != NULL) { if (p->val == q->val){} else { p->next = q; p = q; } q = q->next; } p->next = q; return head; }