p129 链表划分(leetcode 86)

一:解题思路

Time:O(n),Space:O(1)

二:完整代码示例 (C++版和Java版)

C++:

class Solution {
public:
    ListNode* partition(ListNode* head, int x) 
    {
        if (head == NULL) return NULL;
        ListNode* smaller = new ListNode(0);
        ListNode* greater = new ListNode(0);
        ListNode* ps = smaller;
        ListNode* pg = greater;
        for (ListNode* p = head; p != NULL; p = p->next)
        {
            if (p->val < x)
            {
                ps->next = p;
                ps = ps->next;
            }
            else
            {
                pg->next = p;
                pg = pg->next;
            }
        }

        ps->next = greater->next;
        pg->next = NULL;

        return smaller->next;
    }
};

Java:

class Solution {
        public ListNode partition(ListNode head, int x) 
        {
              if(head==null) return null;
              ListNode smaller=new ListNode(0);
              ListNode greater=new ListNode(0);
              ListNode ps=smaller;
              ListNode pg=greater;
              for(ListNode p=head;p!=null;p=p.next)
              {
                  if(p.val<x)
                  {
                      ps.next=p;
                      ps=ps.next;
                  }
                  else
                  {
                      pg.next=p;
                      pg=pg.next;
                  }
              }
              
              ps.next=greater.next;
              pg.next=null;
              
              return smaller.next;
        }
    }

 

posted @ 2020-04-15 15:47  repinkply  阅读(148)  评论(0)    收藏  举报