给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
思路:
递归,首先写出终止条件当链表为空或者链表遍历完后结束。递归为head->next,head->next已经指向一个去重的链表了。重点思考返回什么,应该返回一个去重的链表的头节点。因此这一步应该做的是判断当前的head和head->next是否相等,如果相等则说明重了,返回head->next,否则返回head。递归详细讲解
/**
* 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;
}
head->next=deleteDuplicates(head->next);
return head->val==head->next->val? head->next:head;
}
};
迭代,定义一个工作指针。遍历整个链表中进行判断即可。
/**
* 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 *cur=head;
while(cur!=NULL && cur->next!=NULL){
if(cur->val==cur->next->val){
cur->next=cur->next->next;
}
else{
cur=cur->next;
}
}
return head;
}
};