1. 程式人生 > >LeetCode Day21 Swap Nodes in Pairs

LeetCode Day21 Swap Nodes in Pairs

法一:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode *pb=head,*pf=head->next,*tmp;
        head=pf;
        while(1){
            tmp=pb;
            pb->next=pf->next;
            pf->next=
pb; pb=pb->next; if(!pb || !pb->next) break; else{ pf=pb->next; tmp->next=pf; } } return head; } };

法二:迭代

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if
(head==NULL || head->next==NULL) return head; ListNode *t=head->next; head->next=swapPairs(head->next->next); t->next=head; return t; } };

法三:
建立一個節點pre,用來存放上一次的尾部

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *
dummy=new ListNode(-1),*pre=dummy; dummy->next=head; while(pre->next && pre->next->next){ ListNode *t=pre->next->next; pre->next->next=t->next; t->next=pre->next; pre->next=t; pre=t->next; } return dummy->next; } };