-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbsolute List Sorting.java
More file actions
119 lines (105 loc) · 2.4 KB
/
Absolute List Sorting.java
File metadata and controls
119 lines (105 loc) · 2.4 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
//{ Driver Code Starts
import java.util.*;
import java.io.*;
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
public class Absolute_List_Sort
{
Node head;
/* Function to print linked list */
void printList(Node head,PrintWriter out)
{
Node temp = head;
while (temp != null)
{
out.print(temp.data+" ");
temp = temp.next;
}
out.println();
}
/* Inserts a new Node at front of the list. */
public void addToTheLast(Node node)
{
if (head == null)
head = node;
else
{
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
/* Drier program to test above functions */
public static void main(String args[])throws IOException
{
/* Constructed Linked List is 1->2->3->4->5->6->
7->8->8->9->null */
// Scanner sc = new Scanner(System.in);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
// int t=sc.nextInt();
int t=Integer.parseInt(in.readLine().trim());
while(t>0)
{
// int n = sc.nextInt();
int n=Integer.parseInt(in.readLine().trim());
Absolute_List_Sort llist = new Absolute_List_Sort();
//int n=Integer.parseInt(br.readLine());
// int a1=sc.nextInt();
String s[]=in.readLine().trim().split(" ");
int a1=Integer.parseInt(s[0]);
Node head= new Node(a1);
Node temp=head;
for (int i = 1; i < n; i++)
{
// int a = sc.nextInt();
int a=Integer.parseInt(s[i]);
temp.next=new Node(a);
temp=temp.next;
}
Solution gfgobj = new Solution();
llist.head = gfgobj.sortList(head);
llist.printList(llist.head,out);
t--;
}
out.close();
}
}
// } Driver Code Ends
/* The structure of the node of the Linked List is
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
*/
class Solution
{
Node sortList(Node head) {
// Your code here
Node fast=head;
Node slow=null;
while(fast!=null)
{
if(fast.data<0 && fast!=head)
{
slow.next=fast.next;
fast.next=head;
head=fast;
fast=slow.next;
}
else
{
slow=fast;
fast=fast.next;
}
}
return head;
}
}