您的位置:首页 > Web前端 > Node.js

链表 Swap Nodes in Pairs

2015-04-09 16:54 253 查看
思想:

创建一个辅助头结点简便编程。

下一轮swap中若first为NULL,则second直接设为NULL。

/**
 * 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) // at least two nodes, if not, return 
            return head;
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *prev,*first,*second;
        prev = dummy;
        first = prev->next;
        second = first->next;
        while(second != NULL) {
            prev->next = second;
            first->next = second->next;
            second->next = first;
           
            prev = first;
            first = first->next;
            second = (first == NULL ? NULL : first->next);
        }
        return dummy->next;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: