2019.1.19
题目描述:
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
这题就是删除链表中重复的元素,并且都已经帮你排好序了,很简单的一道题,没啥多说的。。。
解法一:
1.若是空链表或链表只有一个元素,返回head;
3.用pre与p双指针遍历,在p不为空的条件下循环,若pre的值等于p的值,则将pre指向p->next,不相等则pre后移到p的位置;p后移一个元素
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||head->next==NULL) return head;
ListNode* pre=head,*p=head->next;
while(p!=NULL){
if(pre->val==p->val){
pre->next=p->next;
}
else
pre=p;
p=p->next;
}
return head;
}
};
执行时间:8ms