利用 双指针 确定 中间的节点,以中间节点为界限,将链表分割为上下两个部分。
随后将 后半部分反转
最后一步 : 合并 l1 和 l2。
/** * 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){
return;
}
// 得到中间节点
ListNode mid = myMidNode(head);
// 分割链表
ListNode l1 = head;
ListNode l2 = mid.next;
mid.next = null;
// 下部分链表 反转
l2 = myReverse(l2);
// 上下两部分链表合并
mergeLinked(l1,l2);
}
public static void mergeLinked(ListNode l1,ListNode l2){
ListNode l1_tmp = null;// 用来记录 l1 的 next
ListNode l2_tmp = null;// 用来记录 l2 的 next
while(l1!=null && l2 != null){
l1_tmp = l1.next;
l2_tmp = l2.next;
l1.next = l2;
l1 = l1_tmp;
l2.next = l1;
l2 = l2_tmp;
}
}
public static ListNode myReverse(ListNode head){
ListNode prev = null;
ListNode cur = head;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;
}
public static ListNode myMidNode(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow =slow.next;
}
return slow;
}
}
/** * 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){
return;
}
List<ListNode> list = new ArrayList<>();
ListNode node = head;
while(node!=null){
list.add(node);
node = node.next;
}
int n = list.size();
int j = n -1;
int i = 0;
while(i < j){
list.get(i).next = list.get(j);
i++;
if(i == j){
break;
}
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/DarkAndGrey/article/details/122158484
内容来源于网络,如有侵权,请联系作者删除!