问题:
难度:medium
说明:
输入一个链表,要求他的排序出现这样的变化,L(0) > L(1) > L(2) > L(3)...... 变成 L(0) > L(N - 1) > L(1) > L(N - 2) > L(2) ...... > L(N - i) > L(i)。
问题链接:https://leetcode.com/problems/reorder-list/
相关问题:
Reverse Words in a String(将字符串单词顺序反转):https://blog.csdn.net/qq_28033719/article/details/107386312
Reverse Linked List(反转链表):https://blog.csdn.net/qq_28033719/article/details/105010066
输入案例:
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
我的代码:
其实就基于循环和下一个的操作处理就行,什么时候才用下一个节点,要什么算是处理完毕,同时面向数据编程,继续使用数组省事。
class Solution {
private static int[] arr = new int[(int)Math.pow(2, 15)]; // 面向数据编程
public void reorderList(ListNode head) {
int index = 0;
ListNode temp = null;
if(head != null) temp = head.next;
while(head != null) { // 把值放数组内
arr[index ++] = head.val; head = head.next;
}
int e = index >> 1; // 只取一半
for(int i = 1;i <= e;i ++) {
temp.val = arr[index - i];
temp = temp.next;
if(temp != null) { // 什么时候用下一个节点
temp.val = arr[i];
temp = temp.next;
}
}
}
}