-
Notifications
You must be signed in to change notification settings - Fork 15
/
rehashing.java
60 lines (55 loc) · 1.55 KB
/
rehashing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param hashTable: A list of The first node of linked list
* @return: A list of The first node of linked list which have twice size
*/
public ListNode[] rehashing(ListNode[] hashTable) {
// write your code here
int oldCap = hashTable.length;
int newCap = oldCap * 2;
ListNode[] rehashed = new ListNode[newCap];
for (int i = 0; i < oldCap; i++) {
ListNode cur = hashTable[i];
if (cur != null) {
ListNode runner = cur;
while (runner != null) {
ListNode next = runner.next;
runner.next = null;
setNode(rehashed, runner);
runner = next;
}
}
}
return rehashed;
}
void setNode(ListNode[] table, ListNode elem) {
int key = elem.val;
int cap = table.length;
int index;
if (key < 0) {
index = (key % cap + cap) % cap;
} else {
index = key % cap;
}
if (table[index] == null) {
table[index] = elem;
} else {
ListNode runner = table[index];
while (runner.next != null) {
runner = runner.next;
}
runner.next = elem;
}
}
};