(链表) 83. Remove Duplicates from Sorted List

时间:2022-12-31 03:57:50

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 --------------------------------------------------------------------------------
这个题说的是把一个已经排序好的链表删掉重复值,注意题目中的sorted linked list,指的是以及排序好的,所以不必想的那么复杂。
C++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//map<int,int> mp;
ListNode* deleteDuplicates(ListNode* head) {
/*
ListNode *p = new ListNode(-1);
p->next = head;
ListNode *cur;
cur = p;
while(cur->next){
if(!mp.count(cur->next->val)){
mp[cur->next->val]++;
cur = cur->next;
}
else{
cur->next = cur->next->next;
}
}
return p->next;
*/
      
     //如果所在的节点和下一个节点的值相等,删除下一个节点,否则,指向这个结点的指针移动到下一个节点的位置。
ListNode *cur = head;
while(cur && cur ->next){
if(cur->val == cur->next->val){
cur->next = cur->next->next;
}
else
cur = cur->next;
}
return head;
}
};