leetcode-24,交换链表相邻节点,递归实现
2018-04-02 10:48
489 查看
给定一个链表,对每两个相邻的结点作交换并返回头节点。例如:
给定
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head==null||head.next==null) {
return head;
}
ListNode temp = head.next;
head.next = temp.next;
temp.next = head;
head.next = swapPairs(head.next);
return temp;
}
}
给定
1->2->3->4,你应该返回
2->1->4->3。你的算法应该只使用额外的常数空间。不要修改列表中的值,只有节点本身可以更改。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head==null||head.next==null) {
return head;
}
ListNode temp = head.next;
head.next = temp.next;
temp.next = head;
head.next = swapPairs(head.next);
return temp;
}
}
相关文章推荐
- leetcode24,交换链表相邻的节点
- LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Java单链表基本操作(九)--交换相邻节点对的值
- 单链表相邻两个节点之间交换顺序
- [LeetCode] 24. Swap Nodes in Pairs 交换相邻结点 @python
- 链表的快速排序(递归,交换节点数据)
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- LeetCode 226. Invert Binary Tree 递归、指针交换 思考链表的交换
- Java实现-两两交换链表中的节点
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- 非递归实现交换二叉树的左右子节点
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- 交换链表中的相邻节点
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- 带头节点链表的反转 循环和递归 C#实现
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- Swap Nodes in Pairs 链表交换相邻的节点