Q:Write code to partiton a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.
A:双链表,其中一个记录小于x的置的节点,剩下的节点记录在第一个链表下,最后将第一个链表的尾节点指向第二个链表的head
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *init(int a[], int n) {
ListNode *head = NULL;
ListNode *p = NULL;
for (int i = 0; i < n; i++) {
ListNode *cur = new ListNode(a[i]);
if (i == 0) {
head = cur;
p = cur;
}
p->next = cur;
p = cur;
}
return head;
}
ListNode *partition(ListNode *head, int x) {
ListNode small_dummy(-1);
ListNode big_dummy(-1);
ListNode *small = &small_dummy;
ListNode *big = &big_dummy;
for (ListNode *cur = head; cur; cur = cur->next) {
if (cur->val < x) {
small->next = cur;
small = small->next;
} else {
big->next = cur;
big = big->next;
}
}
small->next = big_dummy.next;
big->next = NULL;
return small_dummy.next;
}
void printList(ListNode *head) {
ListNode *p = head;
for( ; p; p = p->next) {
cout<<p->val<<" ";
}
cout<<endl;
}
int main() {
int a[10] = {1,4,3,2,5,2};
ListNode *head = init(a, 6);
printList(head);
head = partition(head, 3);
printList(head);
return 0;
}