题目
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
我的题解
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* small = NULL;
ListNode* big = NULL;
ListNode* s_cur = NULL;
ListNode* b_cur = NULL;
ListNode* cur = pHead;
while(cur != NULL) {
if((cur->val) < x) {
if(small == NULL) {
small = cur;
s_cur = small;
} else {
s_cur->next = cur;
s_cur = s_cur->next;
}
} else {
if(big == NULL) {
big = cur;
b_cur = big;
} else {
b_cur->next = cur;
b_cur = b_cur->next;
}
}
cur = cur->next;
}
if(s_cur == NULL)
return big;
s_cur->next = big;
if(b_cur != NULL)
b_cur->next = NULL;
return small;
}
};