这次比较简单是用C++写的
题目描述:
- Total Accepted: 171796
- Total Submissions: 436956
- Difficulty: Easy
- Contributor: LeetCod
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
.
Subscribe to see which companies asked this question.
这道题比较简单,就是链表的操作,检查两个相邻元素是否相同,相同删除即可
code:
/**
* 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) {
if(head == NULL)
return NULL;
ListNode* temp1 = head;
ListNode* temp2 = temp1->next;
while( temp2 != NULL){
if(temp2->val == temp1->val)
temp1->next = temp2->next;
else
temp1 = temp1->next;
temp2 = temp2->next;
}
return head;
}
};