题解 | #划分链表#

划分链表

https://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f?tpId=117&tqId=37728&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    ListNode* partition(ListNode* head, int x) {
      if (head == nullptr) {
        return head;
      }
      
      auto node = std::make_unique<ListNode>(-1);
      node->next = head;
      
      ListNode *end = node.get();
      
      //  尾结点
      while (end->next) {
        end = end->next;
      }
      
      ListNode *left = node.get(), *right = end;
      
      while (left->next != end) {
        if (left->next->val >= x) {
          right->next = left->next;
          right = right->next;
          left->next = left->next->next;
          right->next = nullptr;
        } else {
          left = left->next;
        }
      } 
      
      if (end->val >= x) {
        right->next = end;
        left->next = end->next;
        end->next = nullptr;
      }
      
      return node->next;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务