-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List 2:Even after Odd LinkedList
79 lines (74 loc) · 1.79 KB
/
Linked List 2:Even after Odd LinkedList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class Solution
{
public static LinkedListNode<Integer> sortEvenOdd(LinkedListNode<Integer> head)
{
LinkedListNode<Integer> eh=null,et=null,oh=null,ot=null;
while(head!=null){
if(head.data%2==0){
if(eh==null && et==null)
{
eh=head;
et=head;
}
else{
et.next=head;
et=head;
}
head=head.next;
}
else{
if(oh==null && ot==null)
{
oh=head;
ot=head;
}
else{
ot.next=head;
ot=head;
}
head=head.next;
}
}
if(oh!=null){
ot.next=eh;
}
else{
return eh;
}
if(eh!=null){
et.next=null;
}
return oh;
}
}
//or
public class Solution
{
public static LinkedListNode<Integer> sortEvenOdd(LinkedListNode<Integer> head)
{ if(head==null)
return head;
if(head.next==null)
return head;
LinkedListNode<Integer> smallHead=sortEvenOdd(head.next);
LinkedListNode<Integer> temp=smallHead;
if(head.data%2==0)
{ if(temp.data%2==0)
{head.next=temp;
return head;}
while(temp.next!=null && temp.next.data%2!=0)
{
temp=temp.next;
}
// if(temp.next==null){
// head.next=temp;
// return head;}
LinkedListNode<Integer> t1=temp.next;
temp.next=head;
head.next=t1;
return smallHead;}
else
{
head.next=smallHead;
return head;}
}
}