宣城市网站集约化建设,公司官网怎样制作,百度网站排名规则,网站百度推广怎么做的24. 两两交换链表中的节点https://leetcode.cn/problems/swap-nodes-in-pairs/ 给你一个链表#xff0c;两两交换其中相邻的节点#xff0c;并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题#xff08;即#xff0c;只能进行节点交换#xff09;。…24. 两两交换链表中的节点https://leetcode.cn/problems/swap-nodes-in-pairs/ 给你一个链表两两交换其中相邻的节点并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题即只能进行节点交换。 示例 1 输入head [1,2,3,4]
输出[2,1,4,3] 代码思路
将奇数位置的节点和偶数位置的分开存放到队列中然后分别出队列奇数偶数各出一个直到出完为止
class Solution {public ListNode swapPairs(ListNode head) {//奇数节点队列QueueListNode odd new LinkedList();//偶数节点队列QueueListNode even new LinkedList();if(headnull||head.nextnull){return head;}// 将奇数和偶数节点分开入队while(true){if(head!null){odd.add(head);headhead.next;}if(head!null){even.add(head);headhead.next;}else{//当head.nextnull时结束whilebreak;}}// 头节点ListNode ansnew ListNode(-1);// 辅助节点ListNode curans;// 出队while(!odd.isEmpty()||!even.isEmpty()){// 偶数位置先出if(!even.isEmpty()){cur.nexteven.poll();curcur.next;}// 奇数位置出队if(!odd.isEmpty()){cur.nextodd.poll();curcur.next;}}cur.nextnull;return ans.next;}
}
148. 排序链表https://leetcode.cn/problems/sort-list/ 给你链表的头结点 head 请将其按 升序 排列并返回 排序后的链表 。 示例 1 输入head [4,2,1,3]
输出[1,2,3,4] class Solution {public ListNode sortList(ListNode head) {ArrayListInteger listnew ArrayList();while(head!null){list.add(head.val);headhead.next;}Integer[] numslist.toArray(new Integer[0]);Arrays.sort(nums);ListNode ansnew ListNode(-1);ListNode curans;for(int i0;inums.length;i){cur.nextnew ListNode(nums[i]);curcur.next;}cur.nextnull;return ans.next;}
}