思想:
创建一个辅助头结点简便编程。
下一轮swap中若first为NULL,则second直接设为NULL。
/**
* 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) // at least two nodes, if not, return
return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *prev,*first,*second;
prev = dummy;
first = prev->next;
second = first->next;
while(second != NULL) {
prev->next = second;
first->next = second->next;
second->next = first;
prev = first;
first = first->next;
second = (first == NULL ? NULL : first->next);
}
return dummy->next;
}
};
本文介绍了一种使用辅助头结点简化编程的方法来实现链表中节点的两两交换。通过迭代方式更新指针,实现相邻节点的位置互换,并考虑了边界情况。
2463

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



