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.

    Hide Tags
     Linked List Two Pointers
     
    思路:双指针,一个指向less,一个指向great,按顺序处理,注意lessNodeHea和greatNodeHead的应用。
    /**
     * 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) {
    
                ListNode lessNodeHead(-1);
                ListNode greatNodeHead(-1);
    
                ListNode *pLess = &lessNodeHead;
                ListNode *pGreat = &greatNodeHead;
    
                while(head)
                {
                    if(head->val < x)
                    {
                        pLess->next = head;
                        pLess = head;
                    }
                    else
                    {
                        pGreat->next = head;
                        pGreat = head;
                    }
                    head = head->next;
                }
    
                pLess->next = greatNodeHead.next;
                pGreat->next = NULL;
                return lessNodeHead.next;
    
             }
     };
  • 相关阅读:
    Python修饰符实践
    回文
    Linux下安装Qt
    Linux下安装PyQT
    Python闭包实践
    杂乱
    windows下脚本转到linux下,文件保存格式要转换
    lua table.sort的bug
    shell截取某段
    coredump
  • 原文地址:https://www.cnblogs.com/diegodu/p/4350606.html
Copyright © 2011-2022 走看看