zoukankan      html  css  js  c++  java
  • Leetcode: 86. Partition List

    Description

    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.

    Example

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

    思路

    • 维护一个结果链表,tmp指向结果链表的表尾,ptr指向结果链表中小于给定x的最后一个数,然后遍历原链表,大于等于x的接到tmp后面,重置tmp。小于x的插入到ptr后面,然后ptr往后走一步,最后记得将表尾置为NULL

    代码

    /**
     * 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) return NULL;
            
            ListNode *cur = head;
            ListNode *res = new ListNode(0);
            ListNode *ptr = res, *next = NULL;
            ListNode *tmp = res;
            while(cur){
               next = cur->next;
               if(cur->val < x){
                    if(cur != ptr->next)
                        cur->next = ptr->next;
                    ptr->next = cur;
                    if(tmp == ptr)
                        tmp = ptr->next;
                    ptr = ptr->next;
               } 
               else{
                   tmp->next = cur;
                   tmp = tmp->next;
               }
               cur = next;
            }
            
            tmp->next = NULL;
            head = res->next;
            delete res;
            return head;
        }
    };
    
  • 相关阅读:

    梯度下降法
    维特比算法
    分治法
    动态规划
    hadoop学习视频
    Java深拷贝浅拷贝
    Android NDK r8 Cygwin CDT 在window下开发环境搭建 安装配置与使用 具体图文解说
    Linux高性能server编程——定时器
    OpenGL进阶演示样例1——动态画线(虚线、实线、颜色、速度等)
  • 原文地址:https://www.cnblogs.com/lengender-12/p/7007659.html
Copyright © 2011-2022 走看看