Home > Java > javaTutorial > body text

Odd-even LinkedList

WBOY
Release: 2024-07-21 12:18:09
Original
1057 people have browsed it

Odd-even LinkedList

Problem

We have to keep index i tracking the node values if i is odd then put them in a different say odd, else put them in a list say even.
At the end connect the last node of the odd list to head of even list

/**
 * 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 ListNode oddEvenList(ListNode head) {
        ListNode odd  = new ListNode(0);
        ListNode even = new ListNode(0);
        ListNode pointerOfOdd = odd;
        ListNode pointerOfEven = even;
        int i =1;
        while(head!=null){
            if(i%2!=0){
                odd.next = new ListNode(head.val);
                odd = odd.next;
            }
            else{
                even.next = new ListNode(head.val);
                even = even.next;
            }
            i++;
            head = head.next;
        }
        odd.next = pointerOfEven.next;

        return pointerOfOdd.next;
    }
}
Copy after login

The above is the detailed content of Odd-even LinkedList. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!