美团优选一面的题目,不是很难,但是细节有挺多的。
代码 #
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
ListNode fast = head.next, slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
while (tmp != null) {
ListNode tmp2 = tmp.next;
tmp.next = slow.next;
slow.next = tmp;
tmp = tmp2;
}
tmp = slow.next;
slow.next = null;
fast=head;
while(tmp!=null){
ListNode tmp2 = tmp.next;
ListNode tmp3 = fast.next;
tmp.next = fast.next;
fast.next = tmp;
fast=tmp3;
tmp=tmp2;
}
// ListNode tmp4 = head;
// while (tmp4 != null) {
// System.out.println(tmp4.val);
// tmp4 = tmp4.next;
// }
}
}