给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你不需要 保留 每个分区中各节点的初始相对位置。
示例 1:

输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2 输出:[1,2]
提示:
[0, 200] 内-100 <= Node.val <= 100-200 <= x <= 200 
代码:
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
- typedef struct ListNode ListNode;
- struct ListNode* partition(struct ListNode* head, int x){
- if(head==NULL){
- return head;
- }
- //创建带头的大小链表
- ListNode*lessHead,*lessTail,*greaterHead,*greaterTail;
- //大小链表的哨兵卫
- lessHead=lessTail=(ListNode*)malloc(sizeof(ListNode));
- greaterHead=greaterTail=(ListNode*)malloc(sizeof(ListNode));
- ListNode*cur=head;
- //遍历原链表,将结点放到大小链表中
- while(cur){
- if(cur->val
- //放到小链表中
- lessTail->next=cur;
- lessTail=lessTail->next;
- }
- else{
- //放到大链表中
- greaterTail->next=cur;
- greaterTail=greaterTail->next;
- }
- cur=cur->next;
- }
- if(greaterTail){
- greaterTail->next=NULL;
- }
- //小链表的尾和大链表的头(第一个有效结点)连接起来
- lessTail->next=greaterHead->next;
- //把动态开辟的空间释放掉
- free(greaterHead);
- ListNode*rethead=lessHead->next;
- free(lessHead);
- return rethead;
- }

理解exit
1、exit的功能为:退出当前运行的程序,并将参数value返回给主调进程。
2、exit(0),exit(1) 和 exit(-1)的区别
- exit(0)表示程序正常退出;除了0之外,其他参数均代表程序异常退出,如:exit(1),exit(-1)。
- exit(1)和exit(-1)是分别返回1和-1到主调程序。
- exit(0)则是返回0。exit(0)表示程序正常退出,非0表示非正常退出。
3、return与exit的区别
- return是语言级别的,它表示了调用堆栈的返回;
- 而exit是系统调用级别的,它表示了一个进程的结束。
return和exit作用大致相同。
在main中:
return v; 与 exit(v); 的效果相同。
但是在其它功能函数中就会有所区别:
return会跳出函数,而exit会结束程序。
即: return是返回函数调用,如果返回的是main函数,则为退出程序 ;
exit是在调用处强行退出程序,运行一次该程序就被强制结束 。
4、通常可以借助exit()的返回值判断程序结束状态,
0表示程序正常退出,
其它值是异常退出,
在退出前可以给出一些提示信息,方便在调试程序时察看出错原因。