Skip to content

Commit 8c7400f

Browse files
authored
Create Linked List Frequency.java
1 parent 2c002d2 commit 8c7400f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Medium/Linked List Frequency.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode frequenciesOfElements(ListNode head) {
13+
Map<Integer, Integer> map = new HashMap<>();
14+
for (ListNode curr = head; curr != null; curr = curr.next) {
15+
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
16+
}
17+
ListNode dummy = new ListNode(-1);
18+
ListNode curr = dummy;
19+
for (Integer key : map.keySet()) {
20+
curr.next = new ListNode(map.get(key));
21+
curr = curr.next;
22+
}
23+
return dummy.next;
24+
}
25+
}

0 commit comments

Comments
 (0)