标签:
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 };
标签:
原文地址:http://www.cnblogs.com/desp/p/4345793.html