143. Reorder List
題目
給出一個單鏈表L:L0→L1→…→Ln-1→Ln,
重排爲:L0→Ln→L1→Ln-1→L2→Ln-2→…
例1:
給出 1->2->3->4, 重排爲: 1->4->2->3.
例2:
給出 1->2->3->4->5, 重排爲: 1->5->2->4->3.
代碼塊
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
ListNode fastNode = head;
int len = 0;
while(fastNode != null){
len++;
fastNode = fastNode.next;
}
ListNode pre = head;
for(int i = 0; i < (len - 1)/2; i++){
pre = pre.next;
}
//fastNode = pre.next;
// ListNode slowNode = head;
fastNode = pre.next.next;
ListNode slowNode = pre.next;
while(fastNode != null){
slowNode.next = fastNode.next;
fastNode.next = pre.next;
pre.next = fastNode;
fastNode = slowNode.next;
}
fastNode = pre.next;
slowNode = head;
pre.next = null;
for(int i = 0; i < (len )/2; i++){
ListNode temp = fastNode.next;
fastNode.next = slowNode.next;
slowNode.next = fastNode;
slowNode= fastNode.next;//忘寫
fastNode = temp;
}
// return ;這句加不加都ok
}
}
代碼分析
本題分爲以下幾個步驟:
第一:獲得鏈表的長度;
第二:找到鏈表的中點;
第三:將中點後的元素進行逆序;
第四:前面取一個,後面取一個。
注意:本題將前面的逆序進行了融合。return head 時 一直出錯,沒有注意到函數的返回值是void,前後不一致,所以編譯錯誤。
return head;
對應着ListNode。
return ;
對應着void。