leetcode86. 分隔链表

#include<queue>
#include<iostream>
using namespace std;

  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
 // 思想: 遍历链表:两个队列分别存小于x的数 一个存大于等于x的数,最后两者连接起来就好了
 // 可以不用 队列存东西,可以直接搞两个头节点 直接链接下去就好了 额
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
    	if(head == nullptr)
    		return nullptr;
        queue<ListNode*> small_queue;
        queue<ListNode*> big_queue;
        ListNode* go = head;
        while(go != nullptr){
        	if(go->val < x){
        		small_queue.push(go);
        	}else{
        		big_queue.push(go);
        	}
        	go = go->next;
        }
        // 弄两个 帮忙做头节点。 在其后面存东西
        ListNode* res1 = new ListNode(0);
        ListNode* res2 = new ListNode(0);
        // 取出 前半段
        go = res1;
        while(!small_queue.empty()){
        	go->next = small_queue.front();
        	small_queue.pop();
        	go = go->next;
        }
        // 后半段
        ListNode* go2 = res2;
        while(!big_queue.empty()){
        	go2->next = big_queue.front();
        	big_queue.pop();
        	go2 = go2->next;
        }
        go2->next = nullptr;
        // 拼接在一起
        if(go != res1){
        	go->next = res2->next;
        	return res1->next;
        }else{
        	return res2->next;
        }
    }
};
int main(){
	ListNode* a1 = new ListNode(1);
	ListNode* a2 = new ListNode(4);
	ListNode* a3 = new ListNode(3);
	ListNode* a4 = new ListNode(2);
	ListNode* a5 = new ListNode(5);
	ListNode* a6 = new ListNode(2);
	a1->next = a2;
	a2->next = a3;
	a3->next = a4;
	a4->next = a5;
	a5->next = a6;
	a6->next = nullptr;
	Solution s;
	ListNode* res = s.partition(a1, 3);
	while(res!=nullptr){
		cout << res->val<<endl;
		res = res->next;
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值