LintCode 96.链表划分
题目说明
思路
从头遍历,找到大于等于x的元素提出来建立一个新链表,再和原来的链表连接。
无法找到其前一个节点。
最终思路
head指针从头到尾遍历该链表的每一个元素
逐个与x进行比较
建立两个头结点
- 链接比x小的元素
- 链接比x大的元素
并通过比那里使之串接起来
最后合并两个链表
/**
* Definition of singly-linked-list:
* 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
ListNode *smallHead = new ListNode(0);
ListNode *bigHead = new ListNode(0);
ListNode *smallRear = smallHead;
ListNode *bigRear = bigHead;
while(head != NULL)
{
if(head->val < x)
{
smallRear->next = head;
smallRear = head;
}
else
{
bigRear->next = head;
bigRear = head;
}
head = head->next;
}
smallRear->next = bigHead->next;
bigRear->next = NULL;
return smallHead->next;
}
};
标准答案
/**
* 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=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) {
ListNode *leftDummy = new ListNode(0);
ListNode *rightDummy = new ListNode(0);
ListNode *leftTail = leftDummy;
ListNode *rightTail = rightDummy;
while (head != NULL) {
if (head->val < x) {
leftTail->next = head;
leftTail = head;
} else {
rightTail->next = head;
rightTail = head;
}
head = head->next;
}
leftTail->next = rightDummy->next;
rightTail->next = NULL;
return leftDummy->next;
}
};