题意:

image.png

解题思路:

  1. 思路:
  2. 1. 定义虚拟头节点指向head节点,保存m-n的前后节点;
  3. 2. 反转m-n之间的那段链表;
  4. 3. 最后连接;

PHP代码实现:

  1. function reverseBetween1($head, $m, $n) {
  2. $dummy = new ListNode(0);
  3. $dummy->next = $head;
  4. $node = $dummy;
  5. //找到需要反转的那一段的上一个节点
  6. for ($i = 1; $i < $m; $i++) {
  7. $node = $node->next;
  8. }
  9. //node.next就是需要反转的这段的起点。
  10. $nextHead = $node->next;// 2->3->4->5
  11. $next = null;
  12. $pre = null;
  13. //反转m到n这一段
  14. for ($i = $m; $i <= $n; $i++) {
  15. $next = $nextHead->next;
  16. $nextHead->next = $pre;
  17. $pre = $nextHead;
  18. $nextHead = $next;
  19. }
  20. //将反转的起点的next指向next。
  21. $node->next->next = $next; //1-2 -> 5
  22. //需要反转的那一段的上一个节点的next节点指向反转后链表的头结点 //1->4
  23. $node->next = $pre;
  24. return $dummy->next;
  25. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func reverseBetween(head *ListNode, m int, n int) *ListNode {
  9. if head == nil || m > n {
  10. return nil
  11. }
  12. dummy := &ListNode{}
  13. dummy.Next = head
  14. node := dummy
  15. for i := 1; i < m; i++ {
  16. node = node.Next
  17. }
  18. //nextHead 第m个节点,也就是将要翻转的节点
  19. nextHead := node.Next
  20. for i := m; i < n; i++ {
  21. tmp := nextHead.Next
  22. nextHead.Next = tmp.Next
  23. tmp.Next = node.Next
  24. node.Next = tmp
  25. }
  26. return dummy.Next
  27. }