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

leetcode 24. Swap Nodes in Pairs

2016-03-08 14:40 621 查看

题意

交换链表相连两个点的值

题解

如题

代码

/**
* 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)
return NULL;
ListNode *now = head->next, *pre = head;

while(now)
{
swap(now->val, pre->val);
if(now->next == NULL || (now->next != NULL && now->next->next == NULL))
break;
pre = now->next;
now = pre->next;

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