LeetCode--Swap Nodes in Pairs

来源:互联网 发布:知乎 未解之谜 编辑:程序博客网 时间:2024/06/01 11:18

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.

方法一:递归法。每次交换前两个,并递归调用交换后面的,交换后面的时候也是先交换前两个,直到不能交换。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL||head->next==NULL) return head;        ListNode* newhead=head->next;        head->next=swapPairs(newhead->next);        newhead->next=head;        return newhead;    }};

方法二:定义一个辅助的头结点和头指针(会发现很方便)。直接正向思维,交换每相邻的两个节点,记录第三个节点更新给当前的头指针的下一个即可,这里的头指针每次都是更新为待交换两个节点前的那个。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL||head->next==NULL) return head;        ListNode dummy(0);        ListNode *cur=&dummy;        while(head&&head->next){            ListNode *next=head->next->next;            cur->next=head->next;            cur=cur->next;            cur->next=head;            cur=cur->next;            head->next=NULL;            head=next;        }        if(head) cur->next=head;        return dummy.next;    }};