zoukankan      html  css  js  c++  java
  • LeetCode 86. Partition List 划分链表 C++

    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:

    Input: head = 1->4->3->2->5->2, x = 3
    Output: 1->2->2->4->3->5

     有点用到了倒置链表II的方法,将符合要求的结点放置在指向pre指针的后面。这道题的思路应该是找到第一个大于等于x值的结点,他前一个位置始终定位pre指针,放置比x小的结点。

    方法一(C++)

     1 class Solution {
     2 public:
     3     ListNode* partition(ListNode* head, int x) {
     4         ListNode* dummy=new ListNode(-1);
     5         dummy->next=head;
     6         ListNode* pre=dummy,* cur=head;
     7         while(pre->next&&pre->next->val<x)
     8             pre=pre->next;
     9         cur=pre;
    10         while(cur->next){
    11             if(cur->next->val<x){
    12                 ListNode* t=cur->next;
    13                 cur->next=t->next;
    14                 t->next=pre->next;
    15                 pre->next=t;
    16                 pre=t;
    17             }
    18             else
    19                 cur=cur->next;
    20         }
    21         return dummy->next;
    22     }
    23 };
  • 相关阅读:
    人物-作家-马克·吐温:马克·吐温
    人物-发明家-特斯拉:尼古拉·特斯拉
    视觉暂留-Info:这些神奇的“视觉暂留”动画,每一幅都让人拍案叫绝!
    视觉暂留:余晖效应/视觉暂留
    mingetty
    mesg
    md5sum
    man.conf
    man
    makemap
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10584290.html
Copyright © 2011-2022 走看看