(一)题目要求:
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
(二)示例:
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
(三)题解:
方法一:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
//方法一:
//(1)遍历链表,将值大于给定值得结点插入新链表p_large
//(2)将p_large与原链表连接
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 *p_current = head,*p_prev = NULL;
//新链表头指针和尾指针
ListNode *p_large = NULL,*p_end = NULL;
while(p_current)
{
if(p_current->val>=x)
{
//结点前结点指向下一个结点(需单独处理头结点)
if(p_current == head)
{
head = p_current->next;
// p_prev = p_current->next;
}
else
p_prev->next = p_current->next;
//将结点插入新链表(需单独处理头结点)
if(!p_large)
{
p_large = p_current;
p_end = p_current;
}
else
{
p_end->next = p_current;
p_end = p_current;
}
//当前结点后移
p_current = p_current->next;
}
//小于x的结点保留
else
{
p_prev = p_current;
p_current = p_current->next;
}
}
//将p_large与原链表连接
if(p_large)
{
if(!head)
head = p_large;
else
p_prev->next = p_large;
//新链表尾结点指向NULL
p_end->next = NULL;
}
return head;
}
};
方法二:
//方法二:
//创建两个链表leftDummy rightDummy 分别保存小于x的结点和大于等于x的结点
//连接两个链表
//注意依旧引入了头结点,避免单独处理头结点
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;
}
//连接两个链表,尾结点指向NULL
leftTail->next = rightDummy->next;
rightTail->next = NULL;
return leftDummy->next;
}
};