链表奇偶数排序(Leetcode328)

2018-11-13  本文已影响0人  zhouwaiqiang

题目

解题方法

代码实现1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode odd = head, even = head.next;
        ListNode oddLast = odd, evenLast = even;//奇偶数链表最后一个节点
        head = head.next.next;
        int count = 0;
        while (head != null) {
            count++;
            ListNode temp = head;
            head = head.next;
            if (count % 2 == 0) {
                temp.next = evenLast.next;
                evenLast.next = temp;
                evenLast = evenLast.next;
            } else {
                temp.next = oddLast.next;
                oddLast.next = temp;
                oddLast = oddLast.next;
            }
        }
        oddLast.next = even;
        evenLast.next = null;
        return odd;
    }
}

代码实现2(和以上类似)

private ListNode oddEvenListBackup(ListNode head) {
        ListNode odd = new ListNode(0);
        ListNode even = new ListNode(0);
        ListNode oddIndex = odd, evenIndex = even;
        ListNode temp = head;//暂存节点索引
        int count = 0;
        while (head != null) {
            count++;
            temp = head;
            head = head.next;
            if (count % 2 == 0) {
                //偶数
                temp.next = evenIndex.next;
                evenIndex.next = temp;
                evenIndex = evenIndex.next;
            } else {
                //奇数
                temp.next = oddIndex.next;
                oddIndex.next = temp;
                oddIndex = oddIndex.next;
            }
        }
        oddIndex.next = even.next;//奇数下一个置为偶数
        return odd.next;
    }
上一篇下一篇

猜你喜欢

热点阅读