关闭

Swap Nodes in Pairs

标签: Swap Nodes in PairsLeetCodeLinked List
156人阅读 评论(0) 收藏 举报
分类:

写法一:

/**
 * 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;
    }
};

效率:


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:38213次
    • 积分:1835
    • 等级:
    • 排名:千里之外
    • 原创:151篇
    • 转载:0篇
    • 译文:0篇
    • 评论:17条
    文章分类
    最新评论