您的位置:首页 > 职场人生

程序员面试金典 2.4 链表分割

2016-02-23 17:31 344 查看

题目

编写代码,以给定值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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息