leetcode 24 两两交换链表中的节点

地址:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
大意:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        
        ListNode *hh = new ListNode(0);
        hh->next = head;
        ListNode *one = hh;
        ListNode *two = hh;
        while(one != NULL && one->next != NULL){
            two = one->next;

            if(two->next != NULL){
                ListNode *second = two->next;
            
                two->next = two->next->next;
                second->next = one->next;
                one->next = second;

            }else
                break;
            
            one = one->next->next;
        }
        return hh->next;
    }
};
posted @ 2020-04-12 03:25  一只小白的进修路  阅读(154)  评论(0)    收藏  举报