面接問題:チェーンテーブルがあり、奇数ビット昇順偶数ビット降順、チェーンテーブルを昇順にする方法
1922 ワード
一、概説
チェーンテーブルがあり、奇数ビット昇順偶数ビット降順で、チェーンテーブルを昇順にする方法があります.
二、考え方
1)チェーンテーブルをパリティ順に2つのチェーンテーブルに分解する
2)偶数ビットを分解したチェーンテーブルの反転
3)2つのチェーンテーブルを結合する
三、コード
チェーンテーブルがあり、奇数ビット昇順偶数ビット降順で、チェーンテーブルを昇順にする方法があります.
二、考え方
1)チェーンテーブルをパリティ順に2つのチェーンテーブルに分解する
2)偶数ビットを分解したチェーンテーブルの反転
3)2つのチェーンテーブルを結合する
三、コード
private static ListNode[] splitList(ListNode head) {
ListNode cur = head;
ListNode head1 = null;
ListNode head2 = null;
ListNode cur1 = null;
ListNode cur2 = null;
int num = 1;
while (head != null) {
if (num % 2 == 1) {
if (cur1 != null) {
cur1.next = head;
cur1 = cur1.next;
} else {
cur1 = head;
head1 = cur1;
}
} else {
if (cur2 != null) {
cur2.next = head;
cur2 = cur2.next;
} else {
cur2 = head;
head2 = cur2;
}
}
head = head.next;
num++;
}
cur1.next = null;
cur2.next = null;
ListNode[] heads = new ListNode[]{head1, head2};
return heads;
}
private static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
private static ListNode mergeLists(ListNode head1, ListNode head2) {
if (head1 == null && head2 == null) {
return null;
}
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
ListNode first = new ListNode(-1);
ListNode cur = first;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
cur.next = head1;
head1 = head1.next;
} else {
cur.next = head2;
head2 = head2.next;
}
}
cur.next = head1 == null ? head2 : head1;
return first.next;
}