fork download
  1. class Node:
  2. def __init__(self, value, next=None):
  3. self.value = value
  4. self.next = next
  5.  
  6. # For testing
  7. def print_linked_list(head):
  8. current = head
  9. while current:
  10. print(current.value, end=" -> " if current.next else "\n")
  11. current = current.next
  12.  
  13. def find_max(head):
  14. maxv = head.value
  15. cur = head.next
  16. while (cur):
  17. maxv = max(maxv, cur.value)
  18. cur = cur.next
  19. return maxv
  20.  
  21. def remove_tail(head):
  22. if head is None:
  23. return None
  24. if head.next is None:
  25. return None
  26.  
  27. current = head
  28. while current.next.next:
  29. current = current.next
  30.  
  31. current.next = None
  32. return head
  33.  
  34. def delete_dupes(head):
  35. temph = Node(0,head)
  36. prev = temph
  37. cur = head
  38. cur2 = head.next
  39. while (cur2):
  40. if (cur.value == cur2.value):
  41. prev.next = cur2.next
  42. cur = cur2.next
  43. cur2 = cur.next
  44. else:
  45. prev = cur
  46. cur = cur2
  47. cur2 = cur2.next
  48. return temph.next
  49.  
  50.  
  51. class Node:
  52. def __init__(self, value, next=None):
  53. self.value = value
  54. self.next = next
  55.  
  56. def has_cycle(head):
  57. slow = head
  58. fast = head.next.next
  59. while (slow.next and fast):
  60. if (slow == fast):
  61. return True
  62. slow = slow.next
  63. fast = fast.next.next
  64. return False
  65. def remove_nth_from_end(head, n):
  66. count = 1
  67. cur = head.next
  68. while (cur):
  69. count+=1
  70. cur = cur.next
  71. temph = Node(0,head)
  72. prev = temph
  73. cur = head
  74. for i in range(count-n):
  75. prev = cur
  76. cur = cur.next
  77. prev.next = cur.next
  78. return temph.next
  79.  
  80. def reverse_first_k(head, k):
  81. temph = Node(0,head)
  82. prev = temph
  83. cur = head
  84.  
  85. for i in range(k-1):
  86. if (cur == None):
  87. break
  88. nexte = cur.next
  89. prev.next = cur.next
  90. prev = cur
  91. cur = nexte
  92. return temph.next
  93. head = Node("apple", Node("cherry", Node("orange", Node("peach", Node("pear")))))
  94.  
  95. print_linked_list(reverse_first_k(head, 3))
  96.  
Success #stdin #stdout 0.1s 14140KB
stdin
Standard input is empty
stdout
cherry -> orange -> peach -> pear