每日一题:143. 重排链表

题目概述:

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行
节点交换。


思路:
用列表实现随机存取

代码:
/**
 * 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) {
        /*思路: 第一个元素指向最后一个元素作为第二个元素
        第二个元素指向原来的第二个元素
        1.先把原来第二个保存一下
        */
        // ListNode tuo = head;
        // ListNode temp = head.next;

        // while(head.next != null)
        // {
        //     head = head.next;
        // }
        // tuo.next = head;
        // head.next = temp;

        //上述错误你必须考虑到每个元素


        //借鉴答案,写出思路
        // 1.判断
        if(head == null || head.next == null)
        {
            return;
        }
        // 2.先把链表中的元素写进list中,方便随机读取
        List<ListNode> list = new ArrayList<>();

        while(head != null)
        {
            list.add(head);
            head =head.next;
        }

        //3.开始对list中的元素进行操作
        int n=list.size();
        int i=0,j=n-1;
        while(i<j)
        {
            //1.第一个元素指向最后一个
            list.get(i).next = list.get(j);
            i++;
            if(i == j)
                break;
            //2.剩下的元素依次排在后面
            list.get(j).next = list.get(i);
            j--;
        }

        list.get(i).next = null;


    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45663946/article/details/109180871