s0024
This commit is contained in:
		@@ -1,11 +1,17 @@
 | 
			
		||||
#include "s0024_swap_nodes_in_pairs.hpp"
 | 
			
		||||
 | 
			
		||||
ListNode* S0024::swapPairs(ListNode* head) {
 | 
			
		||||
  // 只有当 head 和 head->next 都不为空时才翻转
 | 
			
		||||
  // 其它情况都直接返回
 | 
			
		||||
  if (head == nullptr || head->next == nullptr) {
 | 
			
		||||
    return head;
 | 
			
		||||
  }
 | 
			
		||||
  ListNode *newHead = head->next;
 | 
			
		||||
  head->next = swapPairs(newHead->next);
 | 
			
		||||
  newHead->next = head;
 | 
			
		||||
  return newHead;
 | 
			
		||||
  // 从这一行开始就假设 head 和 head->next 都不为空了
 | 
			
		||||
  // 我们首先把从 head->next->next 开始的链表翻转了
 | 
			
		||||
  ListNode* ptr = swapPairs(head->next->next);
 | 
			
		||||
  // 现在我们开始翻转 head 和 head->next
 | 
			
		||||
  ListNode* ans = head->next;
 | 
			
		||||
  head->next->next = head;
 | 
			
		||||
  head->next = ptr;
 | 
			
		||||
  return ans;
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user