forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRehashing.java
43 lines (43 loc) · 1.37 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
/**
* 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
if (hashTable.length <= 0) {
return hashTable;
}
int newcapacity = 2 * hashTable.length;
ListNode[] newTable = new ListNode[newcapacity];
for (int i = 0; i < hashTable.length; i++) {
while (hashTable[i] != null) {
int newindex
= (hashTable[i].val % newcapacity + newcapacity) % newcapacity;
if (newTable[newindex] == null) {
newTable[newindex] = new ListNode(hashTable[i].val);
// newTable[newindex].next = null;
} else {
ListNode dummy = newTable[newindex];
while (dummy.next != null) {
dummy = dummy.next;
}
dummy.next = new ListNode(hashTable[i].val);
}
hashTable[i] = hashTable[i].next;
}
}
return newTable;
}
}