OddEvenLinkedList

  • 2022-12-14
  • 浏览 (523)

OddEvenLinkedList.java 源码

package datastructure.linkedlist.leetcode;

/**
 * 奇偶链表
 */
public class OddEvenLinkedList {

    public ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode evenHead = head.next;
        ListNode odd = head, even = head.next;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }

    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; }
    }
}

你可能感兴趣的文章

AddTwoNumbers

IntersectionLinkedList

LinkedListCycle

0  赞