贵阳网站设计,wordpress1.4,上海做网站最低价,如何免费建设一个网站给定一个单链表 L#xff1a;L0→L1→…→Ln-1→Ln #xff0c; 将其重新排列后变为#xff1a; L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值#xff0c;而是需要实际的进行节点交换。
示例 1:
给定链表 1-2-3-4, 重新排列为 1-4…给定一个单链表 LL0→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(headnull) 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.nextnull;//将链表切割成两个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;}}
}