LeetCode OJ - Partition List

来源:互联网 发布:鬼才大小姐 知乎 编辑:程序博客网 时间:2024/05/17 23:05

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

分析:快排的的基本操作,因为是链表,所以可以采用单向遍历来划分区间,其中交换操作用插入删除代替。


思路一:small指针和cur指针,若cur < x,那么cur插入到small之后

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *remove1(ListNode * last, ListNode *cur) {        if(!cur) return NULL;            last->next = cur->next;        cur->next = NULL;        return cur;    }        void insert(ListNode *small, ListNode *node) {        if(!node) return ;                node->next = small->next;        small->next = node;    }        ListNode *partition(ListNode *head, int x) {        if(!head) return NULL;                ListNode dummy(0);        dummy.next = head;                ListNode *small = &dummy;        while(small->next && small->next->val < x) {            small = small->next;        }                ListNode *cur = small->next;        ListNode *last = small;        while(cur) {            if(cur->val < x) {                ListNode *node = remove1(last, cur);    cur = last;                insert(small, node);    small = small->next;            }                        last = cur;            cur = cur->next;        }                return dummy.next;    }};


思路二:head指针和tail指针,tail指针指向末尾,大于等于x的插入tail之后



思路三:构建两个链表,一个小区链表,一个大区链表,最后合并。数组之所以不这样,是因为会使用额外空间。





0 0