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;
        }
    };
    
  • 相关阅读:
    Python学习
    shell 脚本收藏
    无限级分类接口
    php 过滤多维数组中值为空的字段
    逆波兰表达式3(后缀表达式求值)
    [数据结构]之队列
    最大公约数和最小公倍数
    暗时间阅读笔记
    android判断文件是否是图片文件的方法
    android从assets读取文件的方法
  • 原文地址:https://www.cnblogs.com/lengender-12/p/7007659.html
Copyright © 2011-2022 走看看