编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
#include<iostream>
#include<malloc.h>
using namespace std;
struct ListNode {
int val;
struct ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* partition(ListNode* p, int x) {
// write code here
ListNode* p1 = new ListNode(0); // 小于
ListNode* p2 = new ListNode(0); // 大于等于
ListNode* p1Head = p1;
ListNode* p2Head = p2;
if (!p || !p->next)
return NULL;
p = p->next; // 过滤掉头指针带来的 0
// 下面的算法破坏了原本的数据结构
while (p) {
if (p->val < x) {
p1->next = p;
p1 = p1->next;
}
else {
p2->next = p;
p2 = p2->next;
}
p = p->next;
}
p2->next = NULL;
p1->next = p2Head->next;
return p1Head->next;
}
// 插入元素逆序插入
void insertElem(ListNode* &L) {
ListNode* p, * q;
p = new ListNode(0);
q = new ListNode(0);
L = new ListNode(0);
//L->next = NULL; // 为什么在这里不将其置为NULL 那是因为在结点初始化时已经为NULL了
cin >> p->val;
while (p->val != -1) {
p->next = L->next;
L->next = p;
p = new ListNode(0);
if (!p)
return;
cin >> p->val;
}
}
void printList(ListNode* L) {
while (L) {
cout << L->val << " ";
L = L->next;
}
}
int main() {
ListNode* L;
insertElem(L);
printList(partition(L, 9));
return 0;
}