lintcode-96-链表划分
96-链表划分
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。样例
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null标签
链表 两根指针
思路
遍历一次链表,使用常数级的额外空间,具体做法是:
使用两个指针lessNext,moreNext重新规划链表。使比 x 小的节点和比 x 大的节点重新组成两个新的链表,lessHead,moreHead是这两个新链表的头结点指针,然后,合并这两个链表即可。
code
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
ListNode *partition(ListNode *head, int x) {
// write your code here
if(head == NULL) {
return head;
}
ListNode *lessHead = NULL, *lessNext = NULL;
ListNode *moreHead = NULL, *moreNext = NULL;
ListNode *current = head;
bool isLessHead = true, isMoreHead = true;
while(current != NULL) {
if(current->val < x) {
if(isLessHead){
lessHead = lessNext = current;
isLessHead = false;
}
else {
lessNext->next = current;
lessNext = lessNext->next;
}
}
else {
if(isMoreHead){
moreHead = moreNext = current;
isMoreHead = false;
}
else {
moreNext->next = current;
moreNext = moreNext->next;
}
}
current = current->next;
}
if(lessNext != NULL && moreNext != NULL) {
lessNext->next = moreHead;
moreNext->next = NULL;
return lessHead;
}
else if(lessNext == NULL){
moreNext->next = NULL;
return moreHead;
}
else if(moreNext == NULL) {
lessNext->next = NULL;
return lessHead;
}
}
};