Swap Nodes in Pairs

来源:互联网 发布:火箭发射器升级数据 编辑:程序博客网 时间:2024/05/10 10:25

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.

因为都是2个一组一组变,所以想到用递归会比较方便。在递归的时候只需要改变每次的head,另外再加上组之间的next连接就行。

如果不用递归会比较麻烦。

ListNode *swapPairs(ListNode *head){    if(head==NULL)        return NULL;    if(head->next==NULL)        return head;    ListNode *newHead=head->next;    ListNode *nextHead=head->next->next;    newHead->next=head;    head->next=swapPairs(nextHead);    return newHead;}


0 0