LeetCode 83. 删除排序链表中的重复元素
题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
分析
与上一题基本相同,但是更简单。如果新链表为空或者新链表尾部val与老链表遍历值不同就加入新值即可。我已经写了上一题所以稍作修改即可。理论上这个代码没有这个思路快。
C++代码
/**
* 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 head;
}
if(head->next == NULL){
return head;
}
ListNode* res = new ListNode(0);
ListNode* t = res;
while(head != NULL){
int temp = head->val;
if(head->next == NULL){
t->next = new ListNode(temp);
t = t->next;
break;
}
if(head->next->val == temp){
t->next = new ListNode(temp);
t = t->next;
while(head->next != NULL){
if(head->next->val == temp){
head = head->next;
}else{
break;
}
}
}else{
t->next = new ListNode(temp);
t = t->next;
}
head = head->next;
}
return res->next;
}
};