24. Swap Nodes in Pairs

Problem

leetcode链接problem

Code

不用太解释,就是一个指针的变化而已。第一步的情况和第一步以后的情况略微不同,所以要分开来写,重点是,用草稿纸把这个指针的变化写下来。

 //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 == nullptr || head -> next == nullptr)
        {
            return head;
        }
        ListNode* consthead = head;
        ListNode* pre = head;
        ListNode* now = head -> next;
        int label = 0;
        while(now != nullptr)
        {
            if(label == 0)
            {
                pre->next = now ->next;
                now->next = pre;
                consthead = now;
                if(pre -> next == nullptr)
                {
                    break;
                } else if(pre->next->next ==  nullptr)
                {
                    break;
                } else
                {
                    now = pre ->next;
                }
                label = 1;
            } else{
                pre->next = now->next;
                now->next = pre->next->next;
                pre->next->next = now;
                if(now -> next == nullptr)
                {
                    break;
                } else if(now->next->next ==  nullptr)
                {
                    break;
                } else
                {
                    pre = now;
                    now = now ->next;
                }
            }
        }
        return consthead;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。