当前位置:   article > 正文

算法打卡Day3链表|203.移除链表元素 707.设计链表 206.反转链表

算法打卡Day3链表|203.移除链表元素 707.设计链表 206.反转链表
题目:203.移除链表元素

思路:

代码随想录代码随想录 (programmercarl.com)

  1. def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
  2. dummy_head = ListNode(next=head)
  3. cur = dummy_head
  4. while(cur.next!=None):
  5. if(cur.next.val == val):
  6. cur.next = cur.next.next
  7. else:
  8. cur = cur.next
  9. return dummy_head.next

题目:707.设计链表

思路:

代码随想录:代码随想录 (programmercarl.com)

  1. class Node(object):
  2. def __init__(self, x=0):
  3. self.val = x
  4. self.next = None
  5. class MyLinkedList(object):
  6. def __init__(self):
  7. self.head = Node() # 空的头结点
  8. self.size = 0 # 链表长度
  9. def get(self, index: int) -> int:
  10. if(index < 0 or index >= self.size): # 注意index从0开始
  11. return -1
  12. cur = self.head.next
  13. while index:
  14. cur = cur.next
  15. index -= 1
  16. return cur.val
  17. def addAtHead(self, val: int) -> None:
  18. new_node = Node(val)
  19. new_node.next = self.head.next
  20. self.head.next = new_node
  21. self.size += 1
  22. def addAtTail(self, val: int) -> None:
  23. new_node = Node(val)
  24. cur = self.head
  25. while cur.next:
  26. cur = cur.next
  27. cur.next = new_node
  28. self.size += 1
  29. def addAtIndex(self, index: int, val: int) -> None:
  30. if index == self.size:
  31. self.addAtTail(val)
  32. return
  33. elif index>self.size:
  34. return
  35. elif index<0:
  36. self.addAtHead(val)
  37. return
  38. new_node = Node(val)
  39. cur = self.head
  40. while index:
  41. cur = cur.next
  42. index -=1
  43. new_node.next = cur.next
  44. cur.next = new_node
  45. self.size +=1
  46. def deleteAtIndex(self, index: int) -> None:
  47. if index<0 or index>=self.size:
  48. return
  49. cur = self.head
  50. while index:
  51. cur = cur.next
  52. index -= 1
  53. cur.next = cur.next.next
  54. self.size -= 1

题目:206.反转链表

思路:

  1. 双指针

代码随想录:代码随想录 (programmercarl.com)

  1. def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
  2. pre = None
  3. cur = head
  4. while cur!=None:
  5. tmp = cur.next
  6. cur.next = pre
  7. pre = cur
  8. cur = tmp
  9. return pre
  1. 递归:

  1. def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
  2. def reverse(pre, cur):
  3. if cur == None:
  4. return pre
  5. tmp = cur.next
  6. cur.next = pre
  7. return reverse(cur, tmp)
  8. return reverse(None, head)
总结:
题目看着很简单,但是写的时候中间经常出现一些小问题,需要温故而知新
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/920475
推荐阅读
相关标签
  

闽ICP备14008679号