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。