/**
* @author xienl
* @description 删除有序链表中重复的元素-II
* @date 2022/7/4
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(2)));
System.out.println(solution.deleteDuplicates(listNode));
}
public ListNode deleteDuplicates (ListNode head) {
// write code here
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null){
// 删除所有的相等的结果
if (cur.next.val == cur.next.next.val){
int temp = cur.next.val;
while (cur.next != null && cur.next.val == temp){
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
牛客网:NC24 删除有序链表中重复的元素-II
最新推荐文章于 2024-07-09 18:04:44 发布