网站收录怎么做,医院网站建设的重要性,建筑公司网站电工,网页制作模板百度云1 lc24《两两交换链表中的节点》
1.1 描述 1.2 题解
1.2.1 递归解法
下面的三行注释要理解透彻#xff0c; public ListNode swapPairs(ListNode head) {if(headnull||head.nextnull)return head;// 具体的两两交换过程ListNode nexthead.next; ListNode nextNexthead.next…1 lc24《两两交换链表中的节点》
1.1 描述 1.2 题解
1.2.1 递归解法
下面的三行注释要理解透彻 public ListNode swapPairs(ListNode head) {if(headnull||head.nextnull)return head;// 具体的两两交换过程ListNode nexthead.next; ListNode nextNexthead.next.next; head.nextnextNext;next.nexthead;//将交换后新的尾节点指向下一批节点交换后新的头head.nextswapPairs(nextNext);// 返回交换后新的头节点return next;}1.2.2 非递归解法
public ListNode swapPairs(ListNode head) {ListNode dummynew ListNode();dummy.nexthead;ListNode curdummy;while(cur.next!nullcur.next.next!null){ListNode lcur.next;ListNode rcur.next.next;//swapcur.nextr;l.nextr.next;r.nextl;curl;}return dummy.next;}2 lc25. K 个一组翻转链表
2.1 题目描述 2.2 递归写法 public ListNode reverseKGroup(ListNode head, int k) {if(headnull)return head;ListNode ahead;ListNode bhead;for(int i0;ik;i){if(bnull)return head;bb.next;}//ListNode[]newLinkreverse(a,b);newLink[1].nextreverseKGroup(b,k);return newLink[0];}ListNode[]reverse(ListNode a,ListNode b){ListNode prenull,cura;while(cur!b){ListNode nextcur.next;cur.nextpre;precur;curnext;}//新头新尾return new ListNode[]{pre,a};}