一.题目
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。你应该保留两部分内链表节点原有的相对顺序。
样例:给定链表 1->4->3->2->5->2->null,并且 x=3 返回 1->2->2->4->3->5->null
二.解题思路
定义两个新链表,遍历给定的链表,将每个节点与给定值x比较,比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;
}
ListNode *leftP = new ListNode(0);
ListNode *rightP= new ListNode(0);
ListNode *left = leftP, *right = rightP;
while (head != NULL) {
if (head->val < x) {
left->next = head;
left = head;
} else {
right->next = head;
right = head;
}
head = head->next;
}
right->next =NULL;
left->next = rightP->next;
return leftP->next;
}
};
四,感想
这个题不用排序,只需要判断比给定值大或是小,然后放在两个链表里最后连起来,需要想法新颖构思巧妙.