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

Swap Nodes in Pairs

2016-05-30 11:05 441 查看
struct ListNode {  

    int val;  

    ListNode *next;  

    ListNode(int x) : val(x), next(NULL) {}  

};  

class Solution {  

public:  

    ListNode *swapPairs(ListNode *head) {  

        ListNode** curNext = &head;  

        while(NULL != *curNext && NULL != (*curNext)->next)  

        {  

            ListNode* temp = (*curNext)->next;  

            (*curNext)->next = (*curNext)->next->next;  

            temp->next = *curNext;  

            *curNext = temp;  

            curNext = &(*curNext)->next->next;  

        }  

        return head;  

    }  

};  
在网上搜到了这份代码,用二级指针的方法解决pre节点的指向问题。其中二级指针curNext起了两个作用,一个是持有节点的地址,供其他节点指过来,一个是持有指针的地址,用解运算修饰符*修改指针的指向。

当然,直接用一级指针容易理解一些,不过需要在循环中做一次指针是否为空的判断:

ListNode *swapPairs(ListNode *head) {
ListNode *first, *second, *temp;

if (!head || !head->next) {
return head;

}
else {
first = head;
second = first->next;
head = second;
temp = first;
while (first && second) {
temp->next = second;
first->next = second->next;
second->next = first;
temp = first;
first = first->next;
if (first != NULL) {
second = first->next;

}

}
return head;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: