給定一個單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列后變為: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例 1:
給定鏈表 1->2->3->4, 重新排列為 1->4->2->3.
代碼
/*** 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) {double n = 0;if(head==null) return;ListNode cnt = head;while (cnt != null) {//統計節點數n++;cnt = cnt.next;}ListNode r = head;for (int i = 0; i < Math.ceil(n / 2)-1; i++) {//找出中間節點r = r.next;}ListNode cur = r.next, pre = null;r.next=null;//將鏈表切割成兩個while (cur != null) {//將后面部分的鏈表逆序ListNode temp = cur.next;cur.next = pre;pre = cur;cur = temp;}while (pre != null) {//合并兩個鏈表ListNode np = pre.next, nh = head.next;head.next = pre;pre.next = nh;pre = np;head = nh;}}
}