题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/** * @author Lu.F * @version 1.0 * @date 2022/10/9 9:06 */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param head ListNode类 * @return ListNode类 */ public ListNode oddEvenList (ListNode head) { // write code here // 判断空 if (head == null){ return null; } // 判断只有一个节点 if (head.next == null){ return head; } // 记录奇节点 ListNode p1 = head; // 记录偶节点 ListNode p2 = head.next; // 保存偶节点地址 ListNode pHead2 = p2; while (p2 != null && p2.next != null){ // 奇节点 p1.next = p2.next; p1 = p1.next; // 偶节点 p2.next = p1.next; p2 = p2.next; } // 奇节点接在偶节点前 p1.next = pHead2; return head; } }