算法-重排链表
/**
https://leetcode-cn.com/problems/reorder-list/submissions/
* 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) { if(head == null || head.next == null || head.next.next == null){ return; } // 通过快慢指针方法找到链表中间节点,如果是偶数节点个数,则是前半部分最后一个节点,使用dummy节点方便处理 ListNode dummy = new ListNode(); dummy.next = head; ListNode fast = dummy; ListNode slow = dummy; while(fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } // 链表后半部分反转,头插法 ListNode cur = slow.next.next; ListNode tail = slow.next; while(cur != null){ ListNode midNext = slow.next; slow.next = cur; cur = cur.next; slow.next.next = midNext; } tail.next = null; // 重排 ListNode headPoint = head; while(slow.next != null && slow != headPoint){ ListNode tmpMove = slow.next; slow.next = slow.next.next; ListNode tmpAfterHeadPoint = headPoint.next; headPoint.next = tmpMove; tmpMove.next = tmpAfterHeadPoint; headPoint = headPoint.next.next; } } }
方法二: 递归
/** * 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) { if(head == null || head.next == null){ return; } // 计算链表长度 int size = 0; ListNode headPoint = head; while(headPoint != null){ headPoint = headPoint.next; size ++; } ListNode tail = reverse(head,size); }
// 根据链表长度递归,并在每次递归中返回上层需要处理的尾节点的指针 ListNode reverse(ListNode head, int length){ if(length == 1){ ListNode tmp = head.next; head.next = null; return tmp; } if(length == 2){ ListNode tmp = head.next.next; head.next.next = null; return tmp; } ListNode tail = reverse(head.next,length - 2); ListNode tailNext = tail.next; ListNode tmpHeadNext = head.next; head.next = tail; tail.next = tmpHeadNext; return tailNext; } }