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

LeetCode OJ--Swap Nodes in Pairs

2014-08-16 20:57 363 查看
https://oj.leetcode.com/problems/swap-nodes-in-pairs/

链表的处理

/**
* 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) {
ListNode *dummy = new ListNode(-1);
if(head == NULL)
return dummy->next;

dummy->next = head;

ListNode *tail = dummy;

ListNode *current = head;
ListNode *second = head->next;
while(current && second)
{
tail->next = second;
current->next = second->next;
second->next = current;

current = current->next;
if(current == NULL)
break;
second = current->next;
tail = tail->next;
tail = tail->next;

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