zoukankan      html  css  js  c++  java
  • LeetCode(86) Partition List

    题目

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

    You should preserve the original relative order of the nodes in each of the two partitions.

    For example,
    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5.

    分析

    给定一个链表与一个目标值x,要求对链表结点按照以下要求重排:

    (1)值小于x的结点,按照其原顺序排列与链表头部
    (3)其余值不小于x的结点,按照其原顺序链接与尾部

    AC代码

    class Solution {
    public:
        ListNode* partition(ListNode* head, int x) {
    
            if (!head || !head->next)
                return head;
    
            ListNode *p = head;
            head = NULL;
            ListNode *r = head;
    
            //(1)寻找第一个不小于目标值的节点p,前n个小于x的节点逐个连接到head,保存尾结点r
            while (p && p->val < x)
            {
                if (!head)
                {
                    head = p;
                    r = head;
                }
                else{
                    r->next = p;
                    //保存新链表尾结点
                    r = r->next;
                }           
                p = p->next;
                r->next = NULL;
    
            }//while
    
            //如果此时p为空,已经没有其余节点,返回新链表head
            if (!p)
                return head;
    
            //(2)p节点大于x,从下一个结点开始遍历,将小于x的结点连接到head中,原链表删除该结点
            ListNode *pre = p , *q = p->next;
            while (q)
            {
                if (q->val < x)
                {
    
                    if (!head)
                    {
                        head = q;
                        r = head;
                    }
                    else{
                        r->next = q;
                        //保存新链表尾结点
                        r = r->next;
                    }
    
                    pre->next = q->next;
                    q = q->next;
    
                    r->next = NULL;
                }//if
                else{
                    pre = q;
                    q = q->next;
                }//else
            }//while
    
            //如果此时,原链表还剩余结点,直接连接到r后面即可
            if (p)
            {
                if (!head)
                    return p;
                else
                r->next = p;
            }
    
            return head;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    IDEA 'Error:java: 无效的源发行版: 12' 解决方案
    E Golang语言之网络编程
    E 04 Golang语言之运算符
    ie表单提交提示下载文件
    日期初始化兼容
    IE8兼容问题总结---trim()方法
    es6变量声明和解构赋值
    js的call和apply拾遗
    prop&attr区别和用法,以多选框为例
    es6的箭头函数
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214839.html
Copyright © 2011-2022 走看看