leetcode86

题目:

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

 

解题思路:

首先加一个伪头结点

找到最后一个比x小的结点,把pre指向该结点。

然后往后找,找到比x小的结点就放到pre后面,pre=pre->next。

 

代码:

 class Solution {
  public:
      ListNode* partition(ListNode* head, int x) {
          if(!head) return head;
          ListNode* dummy = new ListNode(-1);
          dummy->next = head;
          ListNode* cur = dummy;
          while(cur->next && cur->next->val < x){
              cur = cur->next;
          }
          ListNode* pre = cur;
          while(cur->next){
              if(cur->next->val < x){
                  ListNode* t = cur->next;
                  cur->next = cur->next->next;
                  t->next = pre->next;
                  pre->next = t;
                  pre = pre->next;
              }else{
                  cur = cur->next;
              }
          }
          return dummy->next;
      }
  };

 






posted @ 2019-04-02 18:02  yxl2019  阅读(86)  评论(0编辑  收藏  举报