File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test partition_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+ struct ListNode * partition (struct ListNode * head , int x ) {
10+ struct ListNode dummy ;
11+ struct ListNode * p = NULL , * start = & dummy , * pivot ;
12+ dummy .next = head ;
13+ for (pivot = head ; pivot != NULL ; pivot = pivot -> next ) {
14+ if (pivot -> val >= x ) {
15+ break ;
16+ }
17+ start = pivot ;
18+ }
19+
20+ struct ListNode * prev ;
21+ for (p = pivot ; p != NULL ; p = p -> next ) {
22+ if (p -> val < x ) {
23+ prev -> next = p -> next ;
24+ p -> next = start -> next ;
25+ start -> next = p ;
26+ start = p ;
27+ p = prev ;
28+ }
29+ prev = p ;
30+ }
31+ return dummy .next ;
32+ }
33+
34+ int main (int argc , char * * argv )
35+ {
36+ if (argc < 2 ) {
37+ fprintf (stderr , "Usage: ./test target n1 n2 n3...\n" );
38+ exit (-1 );
39+ }
40+
41+ int i , target = atoi (argv [1 ]);
42+ struct ListNode * head = NULL ;
43+ struct ListNode * prev = NULL ;
44+ struct ListNode * p ;
45+ for (i = 0 ; i < argc - 2 ; i ++ ) {
46+ p = malloc (sizeof (* p ));
47+ p -> val = atoi (argv [i + 2 ]);
48+ p -> next = NULL ;
49+ if (head == NULL ) {
50+ head = p ;
51+ prev = head ;
52+ } else {
53+ prev -> next = p ;
54+ prev = p ;
55+ }
56+ }
57+ p = partition (head , target );
58+ while (p != NULL ) {
59+ printf ("%d " , p -> val );
60+ p = p -> next ;
61+ }
62+ printf ("\n" );
63+ return 0 ;
64+ }
You can’t perform that action at this time.
0 commit comments