【力扣每日一题】力扣83删除排序链表中的重复元素

题目来源

力扣83删除排序链表中的重复元素

题目描述

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

思路分析

思路一:使用两个指针,last指针指向上一个元素,current指向当前元素,当last指针的valcurrentval值一样时,current后移,不一样则把last指针指向current元素。

思路二:使用一个指针point,当pointpoint的下一个元素val值相同时,pointnext指针指向它再下一个元素(删除point的直接后继节点),反之point指针向后移动。

代码实现

java实现

public class Solution {public ListNode deleteDuplicates(ListNode head) {// 唯一序列的末尾元素ListNode last = head;// 未筛选序列的第一个元素ListNode current = head;while(current != null) {while(current != null && current.val == last.val) {current = current.next;}last.next = current;last = current;}return head;}
}

c++实现

class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {// 唯一序列的末尾元素ListNode* point = head;while (point != nullptr && point->next != nullptr) {if (point->val == point->next->val) {point->next = point->next->next;}else{point = point->next;}}return head;}
};