/**
* 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) {
//创建快慢指针一个前进一步一个前进两步,当快指针到达尾部节点是慢指针到达中间元素
ListNode dummy = new ListNode(0,head);
ListNode fast = dummy;
ListNode slow = dummy;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next;
if(fast.next != null){
fast = fast.next;
}
}
//记录下我们所需要的后段链表的头指针,并且断开两段链表
ListNode back = slow.next;
slow.next = null;
//保存第一个节点,分别交错放入第一个
link(head,reverse(back),dummy);
}
public void link(ListNode pre,ListNode back,ListNode head){
//首先不能改变头节点的指向
ListNode prev = pre;
//交替加入节点
while(back != null && prev != null){
ListNode dump = prev.next;
head.next = prev;
prev.next = back;
head = back;
prev = dump;
back = back.next;
}
if(prev != null){
head.next = prev;
}
}
public ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
链表重排java实现
最新推荐文章于 2024-04-30 01:45:26 发布