码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 2 :Swap Nodes in Pairs

时间:2014-12-04 13:32:21      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   使用   sp   on   

我的代码是这样的:

class Solution {
public:
       ListNode *swapPairs(ListNode *head) 
    {
        const int TRUE = 1;
        const int FALSE = 0;
        ListNode *listA;
        ListNode *listB;
        ListNode *listFront;
        ListNode *listTail;
        bool bFirstTime = TRUE;

        listFront = head;
        while(listFront != NULL)
        {
            
            listA = listFront;
            if(bFirstTime)
            {
                listTail = listFront;
            }
            listB = listFront->next;
            if(!bFirstTime && listB == NULL)
            {
                return head;
            }
            if(bFirstTime && listB==NULL)
            {
                return listA;
            }
            listFront = listFront->next->next;
            if(bFirstTime && listB !=NULL)
            {
                head = listB;
                bFirstTime = FALSE;
            }
            if(!bFirstTime)
            {
                listTail->next = listB;
                listTail = listA;
            }
            listB->next = listA;
            listA->next = listFront;
            
        }
        return head;
    }
};

网上找的大神的代码:

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode *cur = NULL, *next = NULL, *tmp = NULL, *pre = NULL;
        cur = head;
        if(cur != NULL && cur->next != NULL)
            head = cur->next;
        while(cur != NULL)
        {
            if(cur->next == NULL)
            {
                return head;
            }            
            next = cur->next;
            if(pre != NULL)
                pre->next = next;
            tmp = next->next;
            next->next = cur;
            cur->next = tmp;
            pre = cur;
            cur = cur->next;

        }
        return head;
        
    }
};

     这个问题主要考虑的是两个节点交换位置时,后续节点指针信息的保存。A->B->C->D,经过一次变换后B->A->C->D->E,此时不能丢失指向A的指针pTail,因为一次变换后标记指针已经移动到下一次的处理单位,即pA指向C,pB指向D,pFront指向E,第二次交换若没有pTail的变化会成为B->A->C<-D,链表丢失了D元素且交换失败。因此在第二次交换多出的步骤是将只想A的指针pTail->next = pB;pTial = pA;完成正确的首位相连。以上是一个主要的交换思路。
    此外考虑的是程序的结束标志,考虑的是只有一个输入时,和若干个输入时的ptr->next的值是否是NULL,我的程序加入了一个bFirst使得考虑情况很复杂化,观察他人的代码,直接用了if(curr!=NULL && cur->next!=NULL) 来对确定为头节点,这里当只有一个节点时,它不执行。而在循环里边使用if(curr->next == NULL) 来作为结束标志return head; 程序的结构明了。其中pTail的交换如前所述。

    总结:程序的结束条件,初始条件必须明了简单。

 

LeetCode 2 :Swap Nodes in Pairs

标签:des   style   blog   io   ar   color   使用   sp   on   

原文地址:http://www.cnblogs.com/bestwangjie/p/4142467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!