leetcode 143. 重排链表

it2023-11-16  66

给定一个单链表 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; } } }
最新回复(0)