-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvenOddLinkedList.java~
82 lines (67 loc) · 1.21 KB
/
EvenOddLinkedList.java~
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
80
81
82
import java.util.*;
class EvenOddLinkedList{
public class Node{
int info;
Node next;
Node(int i){
info=i;
next=null;
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
EvenOddLinkedList e=new EvenOddLinkedList();
int no=sc.nextInt();
Node head=null;
Node prev=null;
while(no--!=0){
Node n=e.new Node(sc.nextInt());
if(head==null){head=n;}
else prev.next=n;
prev=n;
}
prev=head;
Node lastEven=null;
Node lastOdd=null;
Node firstOdd=null;
while(prev!=null){
while(prev.info%2==0){
lastEven=prev;
if(prev.next!=null) prev=prev.next;
else break;
} //while 2
if(prev.next==null && lastEven==prev)
break;
while(prev.info%2!=0){//odd
if(lastOdd!=null) lastOdd.next=prev;
lastOdd=prev;
if(prev.next!=null)prev=prev.next;
else break;
}// while 3
if(prev.next==null && lastOdd==prev)
break;
//connect
if(lastEven!=null){
if(firstOdd==null)
firstOdd=lastEven.next;
lastEven.next=lastOdd.next;
prev=lastEven.next;
}
else{
if(firstOdd==null)
firstOdd=head;
lastEven=lastOdd.next;
head=lastEven;
prev=lastEven.next;
}
}// while 1
if(lastEven!=null && firstOdd!=null)
lastEven.next=firstOdd;
if(lastOdd!=null)
lastOdd.next=null;
prev=head;
while(prev!=null){
System.out.println(prev.info);
prev=prev.next;}
}
}