Day12 [LeetCode中等] 86. 分隔链表

Day12: [LeetCode中等] 86. 分隔链表

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/partition-list/

思路:

思路就是构造两个链表min和max,分别储存小于x和大于等于x的节点,最后连接两个链表。需要注意的是,当某个链表无节点的时候,要特殊处理一下,总之就是注意边界条件。

代码:

dirty code凑合看吧

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head||head->next==NULL) return head;
        ListNode* p=NULL,*q=NULL,*p_r=NULL,*q_r=NULL,*s=head;
        while(s){
            if(s->val<x){
                if(p_r==NULL){
                    p=s;
                    p_r=s;
                }else{
                    p_r->next=s;
                    p_r=p_r->next;
                }
            }else{
                if(q_r==NULL){
                    q=s;
                    q_r=s;
                }else{
                    q_r->next=s;
                    q_r=q_r->next;
                }
            }
            s=s->next;
        }
        if(!p_r) return q;
        else p_r->next=q;
        if(!q_r) return p;
        else q_r->next=NULL;
        return p;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 553

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103100260