如何免费申请公司网站,建筑工程电影网,旅游网站建设的建议,网站建设招标说明书24. 两两交换链表中的节点 - 力扣#xff08;LeetCode#xff09;
递归写法
做题思路#xff1a;把需要交换的两个数的前一个数作为参数传入#xff0c;然后使用一个变量保存这两个变量的后一个数#xff0c;交换这个两个数#xff0c;最后把第二个数#xff08;原第一…24. 两两交换链表中的节点 - 力扣LeetCode
递归写法
做题思路把需要交换的两个数的前一个数作为参数传入然后使用一个变量保存这两个变量的后一个数交换这个两个数最后把第二个数原第一个数的next指向这个方法next作为参数传入的返回值最后返回第一个数原第二个数。结束条件为最后只剩下一个值或者刚好交换完。
代码
public ListNode swapPairs(ListNode head) {//结束条件if(headnull||head.nextnull){return head;}ListNode next,p,q;phead;qhead.next;nextq.next;q.nextp;p.nextswapPairs(next);return q;
}
迭代写法
做题思路和递归相似。把原本的head前置用于保证链表不断开并且检测是否可以继续进行交换。使用前置节点代替了递归的功能。
代码
public ListNode swapPairs(ListNode head) {ListNode pre,t,p;pretnew ListNode(1,head);while(pre.next!nullpre.next.next!null){headpre.next;ppre.next.next;head.nextp.next;p.nexthead;pre.nextp;prehead;}return t.next;
}