思路
直观来说我们只需维护两个链表 small 和 large 即可,small 链表按顺序存储所有小于 x 的节点,large 链表按顺序存储所有大于等于 x 的节点。遍历完原链表后,我们只要将 small 链表尾节点指向 large 链表的头节点即能完成对链表的分隔。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
struct ListNode* small = malloc(sizeof(struct ListNode));
struct ListNode* large = malloc(sizeof(struct ListNode));
struct ListNode* smallhead = small;
struct ListNode* largehead = large;
while(head != NULL){
if(head->val < x){
small->next = head;
small = head;
}
else{
large->next = head;
large = head;
}
head = head->next;
}
large->next = NULL;
small->next = largehead->next;
return smallhead->next;
}
复杂度分析
- 时间复杂度: O(n),其中 n 是原链表的长度。我们对该链表进行了一次遍历。
- 空间复杂度: O(1)。