题意:

image.png

解题思路:

  1. 思路:
  2. 1. 头部添加虚拟节点;
  3. 2. 快慢指针同时指向虚拟节点;
  4. 3. 快指针先走n步;
  5. 4. 快慢指针同时移动,直到快指针下一个节点为空;
  6. 5. 慢指针的下一个节点指向下下一个节点;
  7. 6. 最后返回虚拟节点的下一个节点即可;

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. function removeNthFromEnd($head, $n) {
  11. $dummy = new ListNode(0); // 首先新建一个链表的结点
  12. $dummy->next = $head;//令这个结点指向head
  13. $fast = $dummy;
  14. $slow = $dummy;
  15. for ($i = 0; $i < $n; $i++) {
  16. $fast = $fast->next;
  17. }
  18. //当快指针指向最后空节点的时候,慢指针刚好指向倒数第n个节点
  19. while ($fast->next != null) {
  20. $fast = $fast->next;
  21. $slow = $slow->next;
  22. }
  23. $slow->next = $slow->next->next;
  24. return $dummy->next;
  25. }
  26. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func removeNthFromEnd(head *ListNode, n int) *ListNode {
  9. dummy := new(ListNode)
  10. dummy.Next = head
  11. fast, slow := dummy, dummy
  12. for i := 0; i <= n; i++ {
  13. fast = fast.Next
  14. }
  15. for fast != nil {
  16. fast = fast.Next
  17. slow = slow.Next
  18. }
  19. slow.Next = slow.Next.Next
  20. return dummy.Next
  21. }