奇偶升降序链表排序
作者:互联网
看到一道题目,还挺有意思
一个链表奇数位上升序,偶数位上降序,不用额外空间让这个链表整体升序,例如:1 8 3 6 5 4 7 2 9,最后输出1 2 3 4 5 6 7 8 9。
其实不算很难,就是题目比较新颖
解:首先分离出奇数链表和偶数链表,偶数链表反转一下,就成为升序了,最后把两条升序链表合并即可(leetcode上这种题也挺经典的)
public class SortList {
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override public String toString() {
return "ListNode{" + "val=" + val + ", next=" + next + '}';
}
}
@Test
public void test() {
//测试 1-8-3-6-5-4-7-2-9
ListNode l9 = new ListNode(9);
ListNode l2 = new ListNode(2, l9);
ListNode l7 = new ListNode(7, l2);
ListNode l4 = new ListNode(4, l7);
ListNode l5 = new ListNode(5, l4);
ListNode l6 = new ListNode(6, l5);
ListNode l3 = new ListNode(3, l6);
ListNode l8 = new ListNode(8, l3);
ListNode head = new ListNode(1, l8);
ListNode ans = sort(head);
System.out.println(ans);
}
public ListNode sort(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode head1 = head, head2 = head.next, pre = head1, cur = head2;
//将奇数偶数链表拆分出来
while (cur != null && cur.next != null) {
ListNode next = cur.next;
cur.next = next.next;
pre.next = next;
pre = pre.next;
cur = cur.next;
}
head2 = reverse(head2);
return merge(head1, head2).next;
}
//反转链表
private ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode root = reverse(head.next);
head.next.next = head;
head.next = null;
return root;
}
//合并两条链表,升序
private ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0), tmp = dummy;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
tmp.next = head1;
head1 = head1.next;
} else {
tmp.next = head2;
head2 = head2.next;
}
tmp = tmp.next;
}
if (head1 != null) {
tmp.next = head1;
}
if (head2 != null) {
tmp.next = head2;
}
return dummy;
}
}
标签:奇偶,head,ListNode,head2,val,next,链表,head1,排序 来源: https://www.cnblogs.com/zjytrhy/p/15055211.html