Sort linked list which is already sorted on absolute values
PROBLEM :
Given a linked list L of N nodes, sorted in ascending order based on the absolute values of its data. Sort the linked list according to the actual values.
Ex: Input : 1 -> -2 -> -3 -> 4 -> -5
Output: -5 -> -3 -> -2 -> 1 -> 4
Input
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case contains a positive integer N denoting the size of linked list. The second line of each test case contains N space separated integers denoting the values of N nodes.
Output
Corresponding to each test case, print out the sorted linked list.
Constraints
1 <= T <= 100
0 < N <= 30
-100 <= L[i] <= 100
Examples
Input
2
3
1 -3 -4
4
0 -2 3 -10
Output
-4 -3 1
-10 -2 0 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* The structure of the Linked list Node is as follows:
struct Node
{
Node* next;
int data;
}; */
void sortList(Node** head)
{
struct Node *temp,*small ;
if((*head)==NULL)
return ;
temp=(*head) ;
while(temp->next!=NULL)
{
if(temp->data>temp->next->data)
{
small=temp->next ;
temp->next=small->next ;
small->next=(*head) ;
(*head)=small ;
}
else
temp=temp->next ;
}
}
---------------------------------------------------------------------------------
Given a linked list L of N nodes, sorted in ascending order based on the absolute values of its data. Sort the linked list according to the actual values.
Ex: Input : 1 -> -2 -> -3 -> 4 -> -5
Output: -5 -> -3 -> -2 -> 1 -> 4
Input
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case contains a positive integer N denoting the size of linked list. The second line of each test case contains N space separated integers denoting the values of N nodes.
Output
Corresponding to each test case, print out the sorted linked list.
Constraints
1 <= T <= 100
0 < N <= 30
-100 <= L[i] <= 100
Examples
Input
2
3
1 -3 -4
4
0 -2 3 -10
Output
-4 -3 1
-10 -2 0 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/* The structure of the Linked list Node is as follows:
struct Node
{
Node* next;
int data;
}; */
void sortList(Node** head)
{
struct Node *temp,*small ;
if((*head)==NULL)
return ;
temp=(*head) ;
while(temp->next!=NULL)
{
if(temp->data>temp->next->data)
{
small=temp->next ;
temp->next=small->next ;
small->next=(*head) ;
(*head)=small ;
}
else
temp=temp->next ;
}
}
---------------------------------------------------------------------------------
Comments
Post a Comment