0
点赞
收藏
分享

微信扫一扫

将给定的单链表\ L L: L_0→L_1→…→L_{n-1}→L_ nL 0​ →L 1​ →…→L n−1​ →L n​ 重新排序为:L_0→L_n →L_1→L_{n-

梦幻之云 2022-01-17 阅读 72
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
    if(head==null||head.next==null)
    {
        return;
    }
        //找到链表的中点,将链表拆分为两个
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null&&fast.next.next!=null)
        {
            //慢指针要先走
            slow=slow.next;
            fast=fast.next.next;
        }
        //slow为中点
        ListNode rightHead=slow.next;
        slow.next=null;
        //倒置右边的节点
        rightHead=reverseList(rightHead);
        //插入到左边的节点
        while(rightHead!=null)
        {
//             head.next=rightHead;
//             rightHead.next=head.next.next;
//             head=head.next;
//             rightHead=rightHead.next;
            //保存rightHead.next
            ListNode temp=rightHead.next;
            //先右边
            rightHead.next=head.next;
            head.next=rightHead;
            //跳一格
            head=rightHead.next;
            rightHead=temp;
        }
}
    public ListNode reverseList(ListNode head)
    {
//链表的倒置,三个指针,头指针,尾结点指针,保存位置的指针
//例如让第二个元素从指向第三个元素变成指向第一个元素
        if(head==null)
        {
            return null;
        }
        ListNode tail=head;
        head=head.next;
        tail.next=null;
        while(head!=null)
        {
            ListNode temp=head.next;
            head.next=tail;
            tail=head;
            head=temp;
        }
        return tail;
    }
}

这个题目体现了对链表的三个操作,一是找到链表的中点值,二是对链表进行倒置,三是对链表进行插入值的操作

举报

相关推荐

0 条评论