/**
* 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) {
// 2015-09-03
if (hashTable == null || hashTable.length == 0) {
return null;
}
int oldSize = hashTable.length;
int newSize = oldSize * 2;
ListNode[] rst = new ListNode[newSize];
for (int i = 0; i < oldSize; i++) {
ListNode curNode = hashTable[i];
while (curNode != null) {
int val = curNode.val;
int newPos = ((val % newSize) + newSize) % newSize; // 确保newPos>0
if (rst[newPos] == null) {
rst[newPos] = new ListNode(val);
} else {
ListNode tail = rst[newPos];
while (tail.next != null) {
tail = tail.next;
}
tail.next = new ListNode(val);
}
curNode = curNode.next;
} // while
} // for
return rst;
}
};
[刷题]Rehashing
最新推荐文章于 2023-08-10 08:00:00 发布