Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/**
* 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 || !head->next) {
return head;
}
ListNode dummy(-1);
dummy.next = head;
auto prev = &dummy;
auto cur = head;
auto next = cur->next;
for (auto prev = &dummy, cur = head, next = cur->next;next; prev = cur, cur = cur->next, next = cur?cur->next:NULL) {
cur->next = next->next;
next->next = prev->next;
prev->next = next;
}
return dummy.next;
}
};
本文介绍了一种链表相邻节点交换算法,该算法仅使用常量空间,并且不修改节点值,只改变节点间的连接关系。通过示例演示了如何实现链表中每两个相邻节点的交换操作。
309

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



