[스밍] 리허싱.

1432 단어 datastructure
[LintCode]Rehashing
/**
 * 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;
    }
};


좋은 웹페이지 즐겨찾기