题目

C++ solution
/**
* 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 || head->next == NULL)
return head;
ListNode* first = head;
ListNode* second = head->next;
first->next = second->next;
second->next = first;
head = second;
ListNode* last = first;
first = first->next;
if (first == NULL)
return head;
second = first->next;
while (second != NULL) {
first->next = second->next;
second->next = first;
last->next = second;
last = first;
first = first->next;
if (first == NULL)
break;
second = first->next;
}
return head;
}
};
简要题解
按链表顺序交换每两个结点的位置,仔细进行指针操作,注意指针越界问题,即可求解。
本文介绍了一种使用C++实现的链表中相邻节点位置互换的算法。通过迭代方式,每次交换两个节点的位置,同时处理边界情况,如链表尾部或空链表。该算法详细展示了如何正确操作指针,避免越界错误。

被折叠的 条评论
为什么被折叠?



