题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode oddEvenList (ListNode head) { // write code here //首先判断节点个数,若不超过2,直接返回就好了 if(head == null || head.next == null){ return head; } //用双指针,相当于把fast的节点删除(其实是保存到数组中,后面再串起来) //要关注的一个点是,将arr中的数组串起来的时候需要把最后一个节点的next设置为null!要不然就死循环了! ListNode slow = head; ListNode fast = head.next; ArrayList<ListNode> arr = new ArrayList<>(); while(fast!=null && fast.next!=null){ arr.add(fast); ListNode temp = fast.next; slow.next = temp; slow = temp; fast = slow.next; } if(fast!=null){ arr.add(fast); } ListNode dummyNode = new ListNode(0); ListNode cur = dummyNode; for(int i=0;i<arr.size();i++){ cur.next = arr.get(i); cur = cur.next; } cur.next = null; slow.next = dummyNode.next; return head; } }