Swap Nodes in Pairs

写法一:

/**
 * 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) {
       ListNode* h1 = head, *parent = NULL, *h3 = NULL;
        while(h1!=NULL && h1->next!=NULL)
        {
            h3 = h1->next->next;
            
            //swap h1 & h1->next
            if(parent == NULL)
                head = h1->next;
            else
                parent->next = h1->next;
            
            h1->next->next = h1;
            h1->next = h3;

            parent = h1;
            h1 = h3;
        }
        return head;
    }
};

写法二:

/**
 * 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(NULL == head || NULL == head->next)
            return head;
        ListNode* h1 = head;
        head = head->next;
        ListNode* h3 = head->next;
        head->next = h1;
        h1->next = h3;
         
        ListNode* parent = h1;
        h1 = h3;
       
        while(h1!=NULL)
        {
            if(h1->next == NULL)
                break;
            h3 = h1->next->next;
            
            //swap h1 & h2
            parent->next = h1->next;
            h1->next->next = h1;
            h1->next = h3;
            
            
            parent = h1;
            h1 = h3;
        }
        return head;
    }
};

效率:


阅读更多
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Swap Nodes in Pairs

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭