标签:
题目链接:https://leetcode.com/problems/odd-even-linked-list/
题目: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 ...
解题思路:题意为给定一个单链表,将基数位置上的元素放在链表的前面,后面是偶数位置上的元素。示例代码如下:
public class Solution { public ListNode oddEvenList(ListNode head) { if(head==null) return null; /** * 定义一个map,存放位置索引和对象的数值 */ Map<Integer,Integer> temp=new HashMap<Integer,Integer>(); ListNode p=head,q=head; int num=0;//链表的总元素个数 for(int i=1;p!=null;) { temp.put(i, p.val); p=p.next; num++; } int oddNum; //奇数位置的元素个数 int evenNum;//偶数位置的元素个数 if(num%2==0) { oddNum=num/2; evenNum=num/2; } else { oddNum=num/2+1; evenNum=num/2; } for(int i=1;i<=oddNum;i++) { /* * 将基数位置的元素填充到链表的前面 */ q.val=temp.get(2*i-1); q=q.next; } for(int i=1;i<=evenNum;i++) { /* * 将偶数位置的元素填充到链表的后面 */ q.val=temp.get(2*i); q=q.next; } return head; } }
【LeetCode OJ 328】Odd Even Linked List
标签:
原文地址:http://blog.csdn.net/xujian_2014/article/details/50781404