题目链接
https://leetcode.com/problems/swap-nodes-in-pairs/
解题思路
直接看代码
代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *first = head, *next, *end, *t;
head = NULL;
while (first != NULL && first->next != NULL) {
//next和first交换
next = first->next;
t = next->next;
next->next = first;
first->next = t;
if (head == NULL) {
head = next;
} else{
end->next = next;
}
end = first;
first = t;
}
return head;
}
};
网友评论