Leetcode Swap Nodes in Pairs

来源:互联网 发布:游族网络 林奇 编辑:程序博客网 时间:2024/05/04 10:34
这题代码写得太丑了。实在不想提。
/** * 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) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if(head == NULL || head->next == NULL)    return head;        ListNode *cur = NULL, *next = NULL, *nHead = NULL, *tmp = NULL, *prev = NULL;        for(cur = head; cur != NULL;){            if(cur->next != NULL)   next = cur->next->next;            else next = NULL;            tmp = cur->next;            if(nHead == NULL) nHead = tmp;            if(tmp != NULL) tmp->next = cur;            cur->next = next;            if(prev != NULL){                if(tmp != NULL)  prev->next = tmp;                else prev->next = cur;            }               prev = cur;            cur = next;        }        return nHead;    }};