swap nodes in pairs
描述
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
解法
要点 递归解决每两个结点递归一次 到最后 若空返回null 若还有一个结点 直接return 两个结点swap 返回后一个结点(交换后向前)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (headnullptr)
return nullptr;
ListNode* der = nullptr;
if(head->nextnullptr){
return head;
}
else{
der = swapPairs(head->next->next);
}
ListNode * secondNode = head->next;
secondNode->next = head;
head->next = der;
return secondNode;
}
};
本文介绍了一种链表操作的算法,通过递归方式实现每两个相邻节点的交换,而不改变节点内的值。示例中,输入链表1->2->3->4,输出为2->1->4->3。此算法适用于计算机科学与数据结构的学习。

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



