Advertisement
Guest User

Untitled

a guest
May 1st, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. package main
  2. //file to implement expanding/shrinking intlist with a map
  3. import "fmt"
  4.  
  5. type IntList struct {
  6. list map[int]int
  7. //for keeping track of placement indices and insertion spots
  8. record map[string]int
  9. }
  10.  
  11. //creates an IntList and returns it
  12. func createIntList() IntList {
  13. lst := IntList{list:make(map[int]int), record:make(map[string]int)}
  14. lst.record["insert"] = 0
  15. lst.record["last"] = -1
  16. return lst
  17. }
  18. //appends a new element to the end of the list, and updates the insertion and last element positions
  19. func (il IntList) push(elem int) {
  20. il.list[il.record["insert"]] = elem
  21. il.record["insert"] += 1
  22. il.record["last"] += 1
  23. }
  24.  
  25. func (il IntList) pop() int {
  26. popped, has := il.list[il.record["last"]]
  27. if has {
  28. delete(il.list, il.record["last"])
  29. il.record["last"] -= 1
  30. il.record["insert"] -= 1
  31. return popped
  32. }
  33. return -1
  34. }
  35.  
  36.  
  37. func main() {
  38. tester := createIntList()
  39. tester.push(5)
  40. tester.push(8)
  41. fmt.Println(tester)
  42. fmt.Println(tester.pop())
  43. fmt.Println(tester)
  44. }
  45. /*{map[0:5 1:8] map[insert:2 last:1]}
  46. 8
  47. {map[0:5] map[last:0 insert:1]}
  48. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement