Leetcode 83. Remove Duplicates from Sorted List-从有序链表中删除重复节点,重复的节点只保留一个
Posted 二十六画生的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 83. Remove Duplicates from Sorted List-从有序链表中删除重复节点,重复的节点只保留一个相关的知识,希望对你有一定的参考价值。
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2] Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3] Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
package com.linkedlist;
/**
* @Author you guess
* @Date 2022/4/1 17:17
* @Version 1.0
* @Desc 删除重复节点(如果有2个节点值相同,只保留1个节点;重复的节点只保留一个)
*/
public class Leetcode_83_RemoveDuplicatesfromSortedList
public static void main(String[] args)
ListNode node72 = new ListNode(7, null);
ListNode node7 = new ListNode(7, node72);
ListNode node6 = new ListNode(6, node7);
ListNode node5 = new ListNode(5, node6);
ListNode node42 = new ListNode(4, node5);
ListNode node41 = new ListNode(4, node42);
ListNode node40 = new ListNode(4, node41);
ListNode node3 = new ListNode(3, node40);
ListNode node22 = new ListNode(2, node3);
ListNode node21 = new ListNode(2, node22);
ListNode node20 = new ListNode(2, node21);
ListNode node11 = new ListNode(1, node20);
ListNode node1 = new ListNode(1, node11);
Leetcode_83_RemoveDuplicatesfromSortedList main = new Leetcode_83_RemoveDuplicatesfromSortedList();
main.printListNode(main.deleteDuplicates(node1));
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List.
* Memory Usage: 41.6 MB, less than 94.40% of Java online submissions for Remove Duplicates from Sorted List.
* <p>
* 每次:head与head.next值相等时,pre.next = head.next
* head与head.next值不相等时,pre=最后一个重复值,head=下一个值
*
* @param head
* @return
*/
public ListNode deleteDuplicates(ListNode head)
ListNode sentinel = new ListNode(0, head);
ListNode pre = sentinel;
while (head != null)
if (head.next != null && head.val == head.next.val)
pre.next = head.next;
head = head.next;
else
pre = pre.next; //pre指向的链表也是连续的
head = head.next;
return sentinel.next;
public void printListNode(ListNode head)
while (head != null)
System.out.println(head.val);
head = head.next;
以上是关于Leetcode 83. Remove Duplicates from Sorted List-从有序链表中删除重复节点,重复的节点只保留一个的主要内容,如果未能解决你的问题,请参考以下文章
leetcode83-Remove Duplicates from Sorted List
[LeetCode] 83. Remove Duplicates from Sorted List
LeetCode83 Remove Duplicates from Sorted List
LeetCode 83 Remove Duplicates from Sorted List