014-链表中倒数第k个结点

用快慢指针:p2p1先走k-11k:间隔了k-1步,然后再一起走,当p2为最后一个时,p1就为倒数第k个数

  1. class ListNode:
  2. def __init__(self, x):
  3. self.val = x
  4. self.next = None
  5. class Solution:
  6. def FindKthToTail(self, head, k):
  7. if not head or k<=0: return None
  8. p1 = head
  9. p2 = head
  10. #设置两个指针,p2指针先走(k-1)步,然后再一起走
  11. while (k-1)>0:
  12. if (p2.next != None):
  13. p2 = p2.next
  14. k -= 1
  15. else:
  16. return None
  17. while (p2.next != None): # 等同while p2.next:
  18. p1 = p1.next
  19. p2 = p2.next
  20. return p1

 

 

015-反转链表(链表转化赋值

思路:变化node.next

假设翻转1->2->3->4->5,(54321)

重要:

  • 1.构建辅助节点head
  • 2.我们将pnext指向tpnext
  • 3.tpnext指向headnext
  • 4.headnext指向tp
  1. class ListNode:
  2. def __init__(self, x):
  3. self.val = x
  4. self.next = None
  5. class Solution:
  6. # 新链表的表头,不是head,是head.next
  7. def ReverseList(self, pHead):
  8. if not pHead:return None
  9. #构建辅助节点head
  10. head = ListNode(0)
  11. head.next = pHead
  12. p = pHead
  13. while p.next != None:
  14. #链表节点转化操作(重要)
  15. tp = p.next
  16. p.next = tp.next
  17. tp.next = head.next
  18. head.next = tp
  19. return head.next

 

posted on 2019-06-20 22:19 5三金 阅读() 评论() 编辑 收藏

版权声明:本文为WuSehun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/WuSehun/p/11061774.html