Saturday, April 1, 2017

Rehashing

这种带next pointer的ListNode 在换位置的时候一定要注意,它后面链接的一系列nodes
如果要对某一个node变换位置,一定要把它后面所连的nodes list进行切断,或者只copy node value

/**
 * 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 == null || hashTable.length <= 0) return hashTable;
        int capacity = hashTable.length * 2;
        ListNode[] result = new ListNode[capacity];
        int hashcode;
        ListNode node, curr;
        for (int i = 0; i < hashTable.length; i++) {
            node = hashTable[i];
           
            while (node != null) {
                hashcode = (node.val % capacity + capacity) % capacity;
                if (result[hashcode] == null) {
                    result[hashcode] = new ListNode(node.val);
                } else {
                    curr = result[hashcode];
                    while(curr.next != null) {
                        curr = curr.next;
                    }
                    curr.next = new ListNode(node.val);
                }
                node = node.next;
            }
        }
        return result;
       
    }
};

No comments:

Post a Comment