链表-Partition List

struct ListNode* partition(struct ListNode* head, int x) { struct ListNode *p1=(struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *p2=(struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *p=head; struct ListNode *r1=p1; struct ListNode *r2=p2; while(p) { if(p->val<x) { r1->next=p; r1=p; } else { r2->next=p; r2=p; } p=p->next; } r2->next=NULL; r1->next=p2->next; return p1->next; }
思路就是申请两个新的指针p1和p2,小于x的链表结点添加在p1后面,大于x的链表结点添加在p2后面,最后,将p2链接在p1后面即可。要注意p1和p2需带有各自的头结点,这样处理起来会方便一些,最后链接时去掉头结点即可。
浙公网安备 33010602011771号