1. 题目
题目参考: 字节跳动高频题——排序奇升偶降链表
给定一个奇数位升序,偶数位降序的链表,将其重新排序。
输入: 1->8->3->6->5->4->7->2->NULL
输出: 1->2->3->4->5->6->7->8->NULL
2. 题解
按照题意, 算法流程可分为三步
-
按奇偶位置拆分链表,得1->3->5->7->NULL和8->6->4->2->NULL
-
反转偶链表,得1->3->5->7->NULL和2->4->6->8->NULL
-
合并两个有序链表,得1->2->3->4->5->6->7->8->NULL
其中 第2步和第3步分别对应的力扣 206. 反转链表 和 21. 合并两个有序链表,而第1步的解法与 328. 奇偶链表 差不多
public class sortOddEvenList {
public class Solution {
public ListNode sortOddEvenList(ListNode head) {
if (head == null) {
return null;
}
// 1. 分割出奇偶链表
ListNode odd = head;
ListNode evenHead = head.next;
ListNode even = head.next;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = even.next.next;
even = even.next;
}
// 注意最后可能 odd 后还有之前的连接, 需要置空
odd.next = null;
// 2. 反转链表
ListNode newEvenHead = reverse(evenHead);
// 3. 合并两个有序链表
return merge(head, newEvenHead);
}
/**
* 反转链表
*
* @param head
* @return
*/
public ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
/**
* 合并两个有序链表
*
* @param h1
* @param h2
* @return
*/
public ListNode merge(ListNode h1, ListNode h2) {
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
while (h1 != null && h2 != null) {
if (h1.val <= h2.val) {
p.next = h1;
p = p.next;
h1 = h1.next;
} else {
p.next = h2;
p = p.next;
h2 = h2.next;
}
}
p.next = h1 == null ? h2 : h1;
return dummy.next;
}
}
public static void main(String[] args) {
Solution solution = new sortOddEvenList().new Solution();
// 建立测试用例 1->8->3->6->5->4->7->2->NULL, 输出结果应为 1->2->3->4->5->6->7->8->NULL
ListNode head = new ListNode(1);
ListNode p1 = new ListNode(8);
ListNode p2 = new ListNode(3);
ListNode p3 = new ListNode(6);
ListNode p4 = new ListNode(5);
ListNode p5 = new ListNode(4);
ListNode p6 = new ListNode(7);
ListNode p7 = new ListNode(2);
head.next = p1;
p1.next = p2;
p2.next = p3;
p3.next = p4;
p4.next = p5;
p5.next = p6;
p6.next = p7;
solution.sortOddEvenList(head);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}