#include<iostream>
using namespace std;
/**
编写代码,以给定值x为基准将链表分割成两部分,
所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,
请返回重新排列后的链表的头指针。
注意:分割以后保持原来的数据顺序不变。
算法:
涉及到链表的问题一定要使用到指针(指向链表节点的指针)
指针curr small larger分别指向原始链表中的当前节点,
small指向所有小于x的节点构成的子链表的当前节点
larger指向所有大于等于x的节点构成的子链表的当前节点
当curr扫描到当前链表尾部时,将两个子链表和并
关于链表的操作,需要掌握:
根据节点类创建链表(这个过程中隐含着向链表中插入新元素)
以及如何从链表中删除特定元素,
**/
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
if(pHead==NULL){
return NULL;
}
ListNode *curr=pHead;
ListNode *small=new ListNode(0);
ListNode *larger=new ListNode(0);
ListNode *small_head=small;
ListNode *larger_head=larger;
while(curr!=NULL){
if(curr->val<x){
ListNode* new_node=new ListNode(curr->val);
small->next=new_node;
small=small->next;
}
else{
ListNode* new_node=new ListNode(curr->val);
larger->next=new_node;
larger=larger->next;
}
curr=curr->next;
}
if(small_head==small){
return larger_head->next;
}
if(larger_head==larger){
return small_head->next;
}
small->next=larger_head->next;
return small_head->next;
}
};
int main(){
ListNode *pHead=new ListNode(0);
ListNode *head=pHead;
int a[3]={6,2,8};
for(int i=0;i<3;i++){
ListNode *new_node=new ListNode(a[i]);
head->next=new_node;
head=head->next;
}
Partition b;
ListNode *out=b.partition(pHead->next,3);
while(out!=NULL){
cout<<out->val<<endl;
out=out->next;
}
return 0;
}