问题描述:
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例:
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
解题思路:
构建两个新的链表,一个放小于x的节点,另一个放大于等于x的节点,用一个循环将原链表按循序放在两个链表里,最后将两个链表接在一起。
代码:
/**
* 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 NULL;
if (head->next== NULL) return head;
ListNode *l, *r, *p;
ListNode *l1, *r1;
p= head;
l= new ListNode(0);
r= new ListNode(0);
l1= l;
r1= r;
while (p!= NULL) {
if (p->val< x) {
l1->next= p;
l1= p;
} else {
r1->next= p;
r1= p;
}
p= p->next;
}
r1->next= NULL;
l1->next= r->next;
return l->next;
}
};
* 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 NULL;
if (head->next== NULL) return head;
ListNode *l, *r, *p;
ListNode *l1, *r1;
p= head;
l= new ListNode(0);
r= new ListNode(0);
l1= l;
r1= r;
while (p!= NULL) {
if (p->val< x) {
l1->next= p;
l1= p;
} else {
r1->next= p;
r1= p;
}
p= p->next;
}
r1->next= NULL;
l1->next= r->next;
return l->next;
}
};