File tree Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test sort_list.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ struct ListNode {
5+ int val ;
6+ struct ListNode * next ;
7+ };
8+
9+ static void recursive (struct ListNode * dummy , struct ListNode * end )
10+ {
11+ if (dummy == NULL || dummy -> next == end ) {
12+ return ;
13+ }
14+
15+ struct ListNode * pivot = dummy -> next ;
16+ struct ListNode * prev = pivot ;
17+ struct ListNode * p = pivot -> next ;
18+ struct ListNode * first = NULL ;
19+
20+ while (p != end ) {
21+ if (p -> val >= pivot -> val ) {
22+ if (first == NULL && p -> val > pivot -> val ) {
23+ first = prev ;
24+ }
25+ prev = p ;
26+ p = p -> next ;
27+ } else {
28+ prev -> next = p -> next ;
29+ p -> next = dummy -> next ;
30+ dummy -> next = p ;
31+ p = prev -> next ;
32+ }
33+ }
34+
35+ recursive (dummy , pivot );
36+ recursive (first , end );
37+ }
38+
39+ static struct ListNode * sortList (struct ListNode * head )
40+ {
41+ struct ListNode dummy ;
42+ dummy .next = head ;
43+ recursive (& dummy , NULL );
44+ return dummy .next ;
45+ }
46+
47+ int main (int argc , char * * argv )
48+ {
49+ int i , count = argc - 1 ;
50+ struct ListNode * head = NULL , * p , * prev ;
51+ for (i = 0 ; i < count ; i ++ ) {
52+ p = malloc (sizeof (* p ));
53+ p -> val = atoi (argv [i + 1 ]);
54+ p -> next = NULL ;
55+ if (head == NULL ) {
56+ head = p ;
57+ } else {
58+ prev -> next = p ;
59+ }
60+ prev = p ;
61+ }
62+
63+ for (p = sortList (head ); p != NULL ; p = p -> next ) {
64+ printf ("%d " , p -> val );
65+ }
66+ printf ("\n" );
67+ return 0 ;
68+ }
You can’t perform that action at this time.
0 commit comments