Discuss
Pick One
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 ...
思路:两个listnode分别指向奇数节点和偶数节点。最后得到两个链表,将偶数节点组成的链表放到奇数节点组成的链表后面。
注意:什么时候退出循环?需要考虑的是由于第一个数是奇数节点,那么奇数节点一定等于偶数节点的个数或者多一个,后一种情况偶数链表最后会指向null,如果此时调用even.next就会抛出异常。所以要用短路与进行判断,一旦odd.next=null(说明even=null)就不必执行even.next. 如果是前一种情况,那么even.next会先为空。
class Solution {
public ListNode oddEvenList(ListNode head) {
if((head==null)||(head.next==null))
return head;
else{
ListNode odd = head, evenhead;
ListNode even = head.next;
evenhead = even;
// while(even.next != null){
while(odd.next!=null && even.next != null){
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenhead;
return head;
}
}
}
本文介绍了一种在O(1)空间复杂度和O(n)时间复杂度下,将单链表中的奇数节点与偶数节点分离的方法。通过使用两个指针分别遍历奇数节点和偶数节点,并在遍历完成后将偶数节点链表连接到奇数节点链表之后。
507

被折叠的 条评论
为什么被折叠?



