LeetCode 24. Swap Nodes in Pairs
原题链接
简单
作者:
柒柒
,
2019-09-29 13:14:59
,
所有人可见
,
阅读 614
C++ 代码
/**
* 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* headPtr = new ListNode(0);
headPtr->next = head;
// 增加一个游标
ListNode* cur = headPtr;
//标记前后两个要交换的节点
ListNode* first = NULL;
ListNode* second = NULL;
//遍历所有节点
while (cur->next != NULL) {
first = cur->next;
if (first == NULL)
break;
second = first->next;
if (second == NULL)
break;
//交换节点
cur->next = second;
first->next = second->next;
second->next = first;
cur = first;
}
return headPtr->next;
}
};