LeetCode24 两两交换链表中的节点
描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例
输入:head = [1,2,3,4]
输出:[2,1,4,3]
提示
- 链表中节点的数目在范围
[0, 100]
内 0 <= Node.val <= 100
***代码1:***迭代
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode p=dummy;
while (head!=null&&head.next!=null){
p.next=head.next;
ListNode tmp=head.next.next;
head.next.next=head;
head.next=null;//避免出现环
head=tmp;
p=p.next.next;
}
if (head!=null)
p.next=head;
return dummy.next;
}
代码2:递归
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;//新的头节点
head.next = swapPairs(newHead.next);//对剩下节点两两交换链接到当前第二个节点的尾部
newHead.next = head;//新的头节点指向第二个节点
return newHead;
}
}