问题
我们必须保持索引 i 跟踪节点值,如果 i 是奇数,则将它们放入不同的奇数中,否则将它们放入偶数列表中。
最后将奇数列表的最后一个节点连接到偶数列表的头部
/** * 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 odd = new ListNode(0); ListNode even = new ListNode(0); ListNode pointerOfOdd = odd; ListNode pointerOfEven = even; int i =1; while(head!=null){ if(i%2!=0){ odd.next = new ListNode(head.val); odd = odd.next; } else{ even.next = new ListNode(head.val); even = even.next; } i++; head = head.next; } odd.next = pointerOfEven.next; return pointerOfOdd.next; } }
以上是奇偶链表的详细内容。更多信息请关注PHP中文网其他相关文章!