Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. class Node {
  2. var val: (Int, Int)
  3. var next: Node?
  4.  
  5. init(_ val: (Int, Int)) {
  6. self.val = val
  7. }
  8. }
  9.  
  10. class LinkedList {
  11. var head: Node?
  12. var tail: Node?
  13.  
  14. func add(_ val: (Int, Int)) {
  15. let node = Node(val)
  16.  
  17. if tail == nil {
  18. tail = node
  19. head = node
  20. } else {
  21. tail!.next = node
  22. tail = node
  23. }
  24. }
  25.  
  26. func search(_ key: Int) -> Node? {
  27. var node = head
  28.  
  29. while node != nil {
  30. if node!.val.0 == key {
  31. return node!
  32. }
  33.  
  34. node = node!.next
  35. }
  36.  
  37. return nil
  38. }
  39.  
  40. func remove(_ key: Int) -> Bool {
  41. let dummy = Node((0, 0))
  42. dummy.next = head
  43. var node = dummy
  44.  
  45. while node.next != nil {
  46. if node.next!.val.0 == key {
  47. node.next = node.next!.next
  48.  
  49. head = dummy.next
  50.  
  51. return true
  52. }
  53.  
  54. node = node.next!
  55. }
  56.  
  57. return false
  58. }
  59. }
  60.  
  61. class HashTable {
  62. public fileprivate(set) var capacity: Int
  63. fileprivate var lists = [LinkedList]()
  64.  
  65. init(_ capacity: Int) {
  66. self.capacity = capacity
  67.  
  68. for _ in 0 ..< capacity {
  69. lists.append(LinkedList())
  70. }
  71. }
  72.  
  73. fileprivate func calcHashcode(_ key: Int) -> Int {
  74. return key % capacity
  75. }
  76.  
  77. func put(_ key: Int, _ value: Int) {
  78. let list = lists[calcHashcode(key)]
  79.  
  80. if let node = list.search(key) {
  81. node.val = (key, value)
  82. } else {
  83. list.add((key, value))
  84. }
  85. }
  86.  
  87. func get(_ key: Int) -> Int? {
  88. let list = lists[calcHashcode(key)]
  89.  
  90. if let node = list.search(key) {
  91. return node.val.1
  92. } else {
  93. return nil
  94. }
  95. }
  96.  
  97. func remove(_ key: Int) -> Bool {
  98. let list = lists[calcHashcode(key)]
  99.  
  100. return list.remove(key)
  101. }
  102.  
  103. func printLists() {
  104. for (i, list) in lists.enumerated() {
  105. print("List: #\(i)")
  106. var node = list.head
  107.  
  108. while node != nil {
  109. print(node!.val)
  110. node = node!.next
  111. }
  112. }
  113. }
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement