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.

    代码:

    struct ListNode {
          int val;
          ListNode *next;
          ListNode(int x) : val(x), next(NULL) {}
      };
    ListNode* partition(ListNode* head, int x)
    {
          if(head==NULL) return NULL;
          ListNode* begin = head;
          ListNode* second = head->next;
          ListNode* second_pre = head;
          while(second!=NULL)
          {
             if(second->val < x)
             {
                if(begin==head&&begin->val >=x)//第一个节点就是比较大的节点 
                {
                        ListNode* head1 = new ListNode(second->val);
                        head1->next = head;
                        head = head1;
                        //删除second指向的节点 
                        second_pre -> next = second -> next;
                        second = second_pre->next;
                        begin = head;
                        
                }
                else if(second_pre->val < x)//连续两个都比较小 
                {
                      second_pre = second;
                      begin = second_pre;
                      second = second->next;
                }
                else
                {
                       
                       second_pre->next = second->next;
                       second->next = begin->next;
                       begin->next = second;
                       second = second_pre->next;
                       begin = begin ->next;
                }
             }
             else
             {
                      second_pre = second;
                      second = second->next;
             }
          } 
          return head;
    }


  • 相关阅读:
    U盘重装苹果OS系统
    iOS Unity3D游戏引擎入门③
    iOS Unity3D游戏引擎入门②
    iOS Unity3D游戏引擎入门①
    iOS 绘图
    iOS 【手势获取cell位置】【点击cell获取indexpath】
    iOS 多手势冲突解决办法
    iOS -- Bug 小集
    iOS 知识点小集
    CoreLocation 框架
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601422.html
Copyright © 2011-2022 走看看