[leetcode]Reorder List-java

注意以下几点

1. 传入为空

 

由于题目要求比较宽泛,所以采用以下两种方式解答

1. 用空间降低复杂度,使用list存储,借助数组编号寻址,重组链表

/**
 * 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){
            return;
        }
        List<ListNode> list = new ArrayList<ListNode>();
        while (head !=null ){
            list.add(head);
            head = head.next;
        }
        ListNode a = new ListNode(-1);
        for(int i=0; i<=(list.size()-1)/2; i++){
            int j = list.size() - 1- i;
            a.next = list.get(i);
            a = a.next;
            a.next = list.get(j);
            a = a.next;
            a.next=null;
        }
    }
}

 

2. 纯链表操作,链表分成前后两段,后段倒序,两段链表进行merge

public void reorderList(ListNode head){
        if(head == null){
            return;
        }
        ListNode t = new ListNode(-1);
        t.next = head;
        ListNode slow = t;
        ListNode fast = t;
        while (fast != null){
            slow = slow.next;
            fast = fast.next;
            if(fast !=null){
                fast = fast.next;
            }
        }
        ListNode tailHead = null;
        ListNode tailP1 = slow.next;
        if(tailP1 == null){
            return;
        }
        slow.next = null;
        if(tailP1.next != null){
            ListNode tailP2 = tailP1.next;
            tailP1.next=null;
            if(tailP2.next != null){
                ListNode tailP3 = tailP2.next;
                while (tailP3 != null){
                    tailP2.next = tailP1;
                    tailP2 = tailP3;
                    tailP1 = tailP2;
                    tailP3 = tailP3.next;
                }
                tailP2.next = tailP1;
            }else {
                tailP2.next = tailP1;
            }
            tailHead = tailP2;
        }else {
            tailHead = tailP1;
        };
        ListNode a = new ListNode(-1);
        while (head !=null && tailHead != null){
            a.next = head;
            head = head.next;
            a.next.next = tailHead;
            tailHead = tailHead.next;
            a=a.next.next;
        }
        if(head!=null){
            a.next = head;
        }
        if(tailHead != null){
            a.next = tailHead;
        }
        System.out.println();
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值