24. 两两交换链表中的节点
文章目录
- 题目描述
- 迭代法
- 递归法
- 参考文献
题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
迭代法
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {if(head==null||head.next==null){return head;}ListNode res=new ListNode(0);res.next=head;ListNode cur=res;while(cur.next!=null&&cur.next.next!=null){ListNode next=head.next;ListNode tmp=next.next;cur.next=next;next.next=head;head.next=tmp;cur=head;head=head.next;}return res.next;}
}
递归法
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {if(head==null||null==head.next){return head;}ListNode next=head.next;head.next=swapPairs(head.next.next);next.next=head;return next;}
}
参考文献
点击跳转
https://www.bilibili.com/video/BV1xa411A76q?p=6&vd_source=0b5b75024b90934f32850d5e16883515