Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to remove duplicate nodes in LeetCode

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to remove duplicate nodes in LeetCode. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

First, remove duplicate node 1, problem description

Write code to remove duplicate nodes from the unsorted linked list. Keep the node that first appeared.

2, example description example 1:

Enter: [1, 2, 3, 3, 2, 1]

Output: [1, 2, 3]

Example 2:

Enter: [1,1,1,1,2]

Output: [1,2]

Tip:

The length of the linked list is in the range of [20000].

List elements are in the range of [0, 20000].

3, the train of thought of solving the problem

Sentinel node, use of LinkedHashSet collection

4, problem solving procedure

Import java.util.LinkedHashSet

Import java.util.Set

Public class RemoveDuplicateNodesTest {

Public static void main (String [] args) {

ListNode L1 = new ListNode (1)

ListNode L2 = new ListNode (2)

ListNode L3 = new ListNode (3)

ListNode L4 = new ListNode (3)

ListNode L5 = new ListNode (2)

ListNode L6 = new ListNode (1)

L1.next = L2

L2.next = L3

L3.next = L4

L4.next = L5

L5.next = L6

ListNode listNode = removeDuplicateNodes (L1)

System.out.println ("listNode =" + listNode)

}

Public static ListNode removeDuplicateNodes (ListNode head) {

If (head = = null | | head.next = = null) {

Return head

}

Set hashSet = new LinkedHashSet ()

While (head! = null) {

HashSet.add (head.val)

Head = head.next

}

ListNode dummyNode = new ListNode (- 1)

ListNode tempNode = dummyNode

For (Integer num: hashSet) {

ListNode listNode = new ListNode (num)

TempNode.next = listNode

TempNode = tempNode.next

}

Return dummyNode.next

}

}

This is how to remove duplicate nodes from the LeetCode shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report