题目要求:
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
思路:
循环两遍,第一遍找比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 head;
ListNode *head1 = new ListNode;
ListNode *q = head1, *p = head; //q循环head1用,p循环head用
while(p != NULL){
if(p->val < x){
ListNode *temp = new ListNode(p->val);
q->next = temp;
q = q->next;
}
p = p->next;
}
p = head;
while(p != NULL){
if(p->val >= x){
ListNode *temp = new ListNode(p->val);
q->next = temp;
q = q->next;
}
p = p->next;
}
return head1->next;
}
};