leetcode题解: Remove Duplicates from Sorted List(已排序单链表去重)
题目:
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
.
说明:给定已排好序的单链表,去重!
1)此链表默认无头节点,head指针指向的是第一个节点
2)链表为空或者只有一个节点时直接返回即可
实现:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *deleteDuplicates(ListNode *head) { 12 //直接返回 13 if(head==NULL||head->next==NULL) return head; 14 ListNode *p=head; 15 ListNode *q=head->next; 16 while(q) 17 { 18 if((p->val)!=(q->val))//不等处理 19 { 20 p->next=q; 21 p=q; 22 q=q->next; 23 } 24 else 25 q=q->next; 26 } 27 p->next=NULL;//p为最后一个节点,后面节点除掉, 28 //所以令p->next为空 29 return head; 30 } 31 };