首頁 > Java > java教程 > 主體

奇偶鍊錶

WBOY
發布: 2024-07-21 12:18:09
原創
828 人瀏覽過

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;
    }
}
登入後複製

以上是奇偶鍊錶的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!