LeetCode-Odd Even Linked List (Java)

来源:互联网 发布:6s电信4g卡显示3g网络 编辑:程序博客网 时间:2024/06/14 17:22


Problem

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given 1->2->3->4->5->NULL,return 1->3->5->2->4->NULL.

Analysis

This problem can be solved by using two pointers. We iterate over the link and move the two pointers.

Odd Even Linked List

Java Solution

public ListNode oddEvenList(ListNode head) {    if(head == null)         return head;     ListNode result = head;    ListNode p1 = head;    ListNode p2 = head.next;    ListNode connectNode = head.next;     while(p1 != null && p2 != null){            ListNode t = p2.next;            if(t == null)                break;             p1.next = p2.next;            p1 = p1.next;             p2.next = p1.next;            p2 = p2.next;    }     p1.next = connectNode;     return result;}

问题分析:这里就是利用奇数和偶数位之间相互错位的位置关系。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode oddEvenList(ListNode head) {        if(head == null)            return head;        ListNode oddHead = head,evenHead =head.next;        ListNode prevOdd = oddHead,prevEven = evenHead;        while(prevOdd.next != null && prevEven.next != null){            prevOdd.next = prevEven.next;            prevOdd = prevOdd.next;            prevEven.next = prevOdd.next;            prevEven = prevEven.next;        }        prevOdd.next = evenHead;        return oddHead;    }}
0 0
原创粉丝点击