https://leetcode.cn/problems/odd-even-linked-list/https://leetcode.cn/problems/odd-even-linked-list/
解题思路:
把第一个和第二个节点分别作为奇数、偶数的头节点,当遇到奇节点,删除,并插入到奇数头节点后,这样偶数的节点自动排好序,最后拼接起来。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode oddEvenList(ListNode head) { ListNode index=head; if(index==null){ return null; } ListNode index2=head.next; if(index2==null){ //保证有两个节点 return index; } int cnt=0; ListNode now=index2.next,pre=index2; while(now!=null){ if(cnt%2==0){ //遇到奇节点 pre.next=now.next; //删除 index.next=now; //加入头节点后 index=index.next; //更新头节点 } cnt+=1; pre=now; now=now.next; } index.next=index2; //拼接偶数头节点 return head; } }