@@ -237,8 +237,50 @@ void q_reverseK(struct list_head *head, int k)
237
237
q_restruct (head );
238
238
}
239
239
240
+ /* meger each elements of queue in ascending/descending order */
241
+ void merge (struct list_head * head ,
242
+ struct list_head * left ,
243
+ struct list_head * right ,
244
+ bool descend )
245
+ {
246
+ while (!list_empty (left ) && !list_empty (right )) {
247
+ const element_t * l = list_entry (left -> next , element_t , list );
248
+ const element_t * r = list_entry (right -> next , element_t , list );
249
+ if (((descend * 2 ) - 1 ) * strcmp (l -> value , r -> value ) > 0 )
250
+ list_move_tail (left -> next , head );
251
+ else
252
+ list_move_tail (right -> next , head );
253
+ }
254
+ if (list_empty (head ))
255
+ list_splice_tail (right , head );
256
+ else
257
+ list_splice_tail (left , head );
258
+ }
259
+
240
260
/* Sort elements of queue in ascending/descending order */
241
- void q_sort (struct list_head * head , bool descend ) {}
261
+ void q_sort (struct list_head * head , bool descend )
262
+ {
263
+ if (!head || list_empty (head ) || list_is_singular (head ))
264
+ return ;
265
+
266
+ struct list_head * slow = head -> next , * fast = head -> next -> next ;
267
+ while (fast != head && fast -> next != head ) {
268
+ slow = slow -> next ;
269
+ fast = fast -> next -> next ;
270
+ }
271
+
272
+ struct list_head l , r ;
273
+ INIT_LIST_HEAD (& l );
274
+ INIT_LIST_HEAD (& r );
275
+
276
+ list_cut_position (& l , head , slow );
277
+ list_splice_init (head , & r );
278
+
279
+ q_sort (& l , descend );
280
+ q_sort (& r , descend );
281
+
282
+ merge (head , & l , & r , descend );
283
+ }
242
284
243
285
/* Remove every node which has a node with a strictly less value anywhere to
244
286
* the right side of it */
0 commit comments