zoukankan      html  css  js  c++  java
  • [LeetCode]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的存于链表head1,大于等于的存于链表head2,合并head1,head2.

    /**
     * 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==NULL) return head;
            ListNode *p=head;
            ListNode *head1=NULL;
            ListNode *head2=NULL;
            ListNode *p1,*p2;
            while(p)
            {
                ListNode *node=new ListNode(p->val);
                if(node->val<x) 
                {
                    if(head1==NULL) 
                    {
                        head1=p1=node;
                    }
                    else
                    {
                        p1->next=node;
                        p1=node;
                    }
                }
                else
                {
                    if(head2==NULL) 
                    {
                        head2=p2=node;
                    }
                    else
                    {
                        p2->next=node;
                        p2=node;
                    }
                }
                p=p->next;
            }
            p1->next=head2;
            if(head1==NULL) return head2;
            return head1;
        }
    };
    

      

  • 相关阅读:
    axios基础用法
    CSS盒子模型
    前端跨域问题解决方案
    跨域-iframe
    swagger UI配置
    React安装和启动
    React 学习笔记
    redis学习笔记
    10个排序算法,待更新
    docker常用命令,持续更新。。。
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3458317.html
Copyright © 2011-2022 走看看