题解 | #链表的奇偶重排#

链表的奇偶重排

http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

  1. 先遍历获取链表长度
  2. 根据长度创建2个数字存放奇数索引与偶数索引的节点值
  3. 再次遍历对数组进行存值
  4. 再再次遍历,对原链表赋值
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode oddEvenList (ListNode head) {
        //1.空链表情况
        if(head==null){
            return null;
        }
        ListNode temp = head;
        int size = 0;
        //统计下有多少节点
        while(temp!=null){
            size++;
            temp = temp.next;
        }
        int rem = size%2;
        int len = size/2;
        //创建建数组存放 奇数与偶数索引 节点的值
        int[] evenArr = new int[len];
        int[] oddArr = new int[len];
        if(rem == 1){
            oddArr = new int[len+1];
        }
        ListNode temp2 = head;
        int index = 1;
        int evenIndex = 0;
        int oddIndex = 0;
        //存值
        while(temp2!=null){
            if(index%2==0){
                evenArr[evenIndex] = temp2.val;
                evenIndex++;
            }else{
                oddArr[oddIndex] = temp2.val;
                oddIndex++;
            }
            index++;
            temp2 = temp2.next;
        }
        ListNode res = head;
        index = 0;
        evenIndex = 0;
        oddIndex = 0;
        //赋值
        while(res!=null){
            if(index<oddArr.length){
                res.val = oddArr[oddIndex++];
            }else{
                res.val = evenArr[evenIndex++];
            }
            index++;
            res = res.next;
        }
        return head;
    }
}
全部评论

相关推荐

投递腾讯云智研发等公司9个岗位
点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务