Easy 18 Remove Duplicates from Sorted List(83)

来源:互联网 发布:猫喜欢臭袜子 知乎 编辑:程序博客网 时间:2024/06/14 17:10

Description
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.

Solution
逐项遍历,删除重复的节点。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* deleteDuplicates(ListNode* head) {      ListNode* p=head;      while(p){          ListNode* q=p->next;          if(q&&q->val==p->val)          {           p->next=q->next;           q=p->next;           continue;          }          p=q;          if(q!=nullptr)q=q->next;      }           return head;           }};
0 0