zoukankan      html  css  js  c++  java
  • 86.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.

    思路:此题的任务是划分链表,比x小的链表节点都出现在比x大或者等于的节点前面,而且还要保持原来的相对位置不要发生变化。我们新建两个链表了l1,l2,遍历原来的链表 ,把值小于x的节点都加入l1,把值大于或者等于x的节点都加入l2,最后将l2连接至l1的后面,所得的链表就是我们所求的结果了。

    1. /**
       * 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 *head1,*head2;
             head1=head2=NULL;
             ListNode *cur1,*cur2;
             cur1=cur2=NULL;
             while(head){
              ListNode *cur=head;
              head=head->next;
              cur->next=NULL;
              if(cur->val<x){
                  if(!head1){
                      head1=cur;
                      cur1=head1;
                  }
                  else{
                      cur1->next=cur;   
                      cur1=cur1->next;
                  }
                  
              }else{
                  if(!head2){
                      head2=cur;
                      cur2=head2;
                  }else{
                      cur2->next=cur;
                      cur2=cur2->next;
                  }
              }
             }
              if(!cur1)
                  return head2;
              cur1->next=head2;
              return head1;
              
              
              
              
          }
      };
  • 相关阅读:
    xxx
    部署在自己的加了分享,试下
    疑问
    去掉分享
    womenzijide_jiafenxiang
    womenzijide2
    womenzijide
    xiugai-去除js注释
    xiugai2
    《设计模式之禅》读书笔记(一)——单例模式
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5024432.html
Copyright © 2011-2022 走看看