LeetCode 83. Remove Duplicates from Sorted List
原题链接
简单
作者:
Ccc1Z
,
2020-07-15 17:23:26
,
所有人可见
,
阅读 427
83.删除重复节点I(只删一个)
思路
- 画图,找到所需要的节点再判断边界情况
- 83题不需要把重复节点全部删除那么就是简单的双指针找到重复节点的区间即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
while(next != null && cur.val == next.val)
next = next.next;
cur.next = next;
cur = next;
}
return head;
}
}
82.删除重复元素II(重复的全部删除)
思路:
- 找到每段重复节点的区间求其长度
- 如果长度为1那么就不重复
- 如果长度>1则重复
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null){
ListNode next = cur.next;
while(next != null && cur.next.val == next.val)
next = next.next;
if(cur.next.next == next)
cur = cur.next;
else
cur.next = next;
}
return dummy.next;
}
}