@@ -245,7 +245,33 @@ void q_sort(struct list_head *head, bool descend) {}
245
245
int q_ascend (struct list_head * head )
246
246
{
247
247
// https://leetcode.com/problems/remove-nodes-from-linked-list/
248
- return 0 ;
248
+ element_t * curr = NULL , * prev = NULL ;
249
+ const element_t * target ;
250
+ struct list_head * pos = NULL ;
251
+
252
+ if (!head || list_empty (head ) || list_is_singular (head ))
253
+ return 0 ;
254
+
255
+ list_for_each_entry (curr , head , list ) {
256
+ /* Release the element in the next round */
257
+ if (prev ) {
258
+ q_release_element (prev );
259
+ prev = NULL ;
260
+ }
261
+
262
+ /* check right side and find if there is greater value */
263
+ if (curr -> list .next )
264
+ pos = curr -> list .next ;
265
+ for (; pos != head ; pos = pos -> next ) {
266
+ target = list_entry (pos , element_t , list );
267
+ if (strcmp (curr -> value , target -> value ) > 0 ) {
268
+ list_del (& curr -> list );
269
+ prev = curr ;
270
+ break ;
271
+ }
272
+ }
273
+ }
274
+ return q_size (head );
249
275
}
250
276
251
277
/* Remove every node which has a node with a strictly greater value anywhere to
@@ -261,5 +287,22 @@ int q_descend(struct list_head *head)
261
287
int q_merge (struct list_head * head , bool descend )
262
288
{
263
289
// https://leetcode.com/problems/merge-k-sorted-lists/
264
- return 0 ;
290
+ if (!head || list_empty (head ))
291
+ return 0 ;
292
+ if (list_is_singular (head ))
293
+ return q_size (list_first_entry (head , queue_contex_t , chain )-> q );
294
+
295
+ queue_contex_t * first , * target = NULL ;
296
+ first = list_first_entry (head , queue_contex_t , chain );
297
+
298
+ /* move each target's queue to first context's queue */
299
+ list_for_each_entry (target , head -> next , chain ) {
300
+ if (target -> id == first -> id )
301
+ break ;
302
+ list_splice_tail_init (target -> q , first -> q );
303
+ }
304
+ q_sort (first -> q , descend );
305
+ head = first -> q ;
306
+
307
+ return q_size (head );
265
308
}
0 commit comments