LeetCode--No.328--Odd Even Linked List

来源:互联网 发布:tps跨境电商是网络传销 编辑:程序博客网 时间:2024/06/05 12:41

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.

You should try to do it in place. 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.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 
The first node is considered odd, the second node even and so on ...

思路:新建一个存储偶数的列表,参数有h2与p2,h2不动,永远指向该列表表头,p2指向该列表对尾。

           head指向原列表表头,p1指向原列表尾部。

边界检测比较恶心。但觉得自己代码写的太啰嗦。从网上又没有看到满意的答案。只能先这样吧。希望日后如果某天我变牛了=。=,可以重新改下这个代码,写的漂亮些。


/** * 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 || head.next == null || head.next.next == null)            return head;        ListNode p1 = head;        ListNode p2 = head.next;        ListNode h2 = p2;        p1.next = p1.next.next;        p1 = p1.next;        while(p1.next != null && p1.next.next != null){            p2.next = p1.next;            p1.next = p1.next.next;            p1 = p1.next;            p2 = p2.next;        }        if (p1.next != null){            p2.next = p1.next;            p2 = p2.next;        }        p1.next = h2;        p2.next = null;        return head;    }}


0 0