題目: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:
Given1->2->3->4->5->NULL
,
return1->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; } } </integer,integer></integer,integer>