Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

这道题有点意思。主要是记住交换后上一个的父节点还没改变呢,所以用递归来做是比较容易处理的。

 1 class Solution {
 2 public:
 3     ListNode *swapPairs(ListNode *head) {
 4         if(head==NULL || head->next==NULL)
 5             return head;
 6         ListNode *temp = head->next;
 7         ListNode *forward = temp->next;
 8         head->next->next = head;
 9         head->next=swapPairs(forward);
10         return temp;
11     }
12 };

 

相关文章:

  • 2021-07-21
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
猜你喜欢
  • 2021-05-21
  • 2022-03-01
  • 2021-09-10
  • 2021-08-20
  • 2021-09-24
相关资源
相似解决方案