题目
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。
返回同样按升序排列的结果链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
eg:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { /** * 时间复杂度 O(n) * 空间复杂度 O(1) */ public ListNode deleteDuplicates(ListNode head) { if (head == null) { return head; } 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 tempVal = cur.next.val; while (cur.next != null && cur.next.val == tempVal) { cur.next = cur.next.next; } } else { cur = cur.next; } } return dummy.next; }}
复制代码
总结
ListNode dummy = new ListNode(-1); dummy.next = head;
// 逻辑处理
return dummy.next;
复制代码
评论