/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode h = new ListNode(1);
h.next = head;
ListNode firstOdd = h;
ListNode even = head;
while(even != null && even.val % 2 != 0){
firstOdd = even;
even = even.next;
}
if(even == null){
return h.next;
}
ListNode nextOdd = firstOdd.next;
ListNode beforeNextOdd = firstOdd;
while(nextOdd != null){
if(nextOdd.val % 2 != 0){
/*remove*/
beforeNextOdd.next = nextOdd.next;
/*insert*/
nextOdd.next = firstOdd.next;
firstOdd.next = nextOdd;
firstOdd = nextOdd;
nextOdd = beforeNextOdd.next;
}else{
beforeNextOdd = nextOdd;
nextOdd = nextOdd.next;
}
}
return h.next;
}
}
链表奇数元素放在偶数元素前面
最新推荐文章于 2021-04-15 11:13:46 发布
该博客介绍了一个解决方案,用于将链表中的奇数元素移到偶数元素之前。通过创建新的头节点并遍历链表,将遇到的每个奇数节点移到前面,实现了奇偶节点的重新排列。
摘要由CSDN通过智能技术生成