给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
输入:head = [1,1,2] 输出:[1,2]
链接:83. 删除排序链表中的重复元素 - 力扣(LeetCode)
第一步,如果遇到了相同的数值,当前的next变成相同节点的next,越过节点达到删除的效果
第二步,如果不相同,往后走一步
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
ListNode cur = head;
while(cur.next != null){
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}