当前位置: 首页 > 文档资料 > LeetCode 题解 >

Linked List - Partition List

优质
小牛编辑
140浏览
2023-12-01

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。

我们可以使用两个链表,p1和p2,以此遍历原链表,如果节点的值小于x,就挂载到p1下面,反之则放到p2下面,最后将p2挂载到p1下面就成了。

代码如下:

  1. class Solution {
  2. public:
  3. ListNode *partition(ListNode *head, int x) {
  4. ListNode dummy1(0), dummy2(0);
  5. ListNode* p1 = &dummy1;
  6. ListNode* p2 = &dummy2;
  7. ListNode* p = head;
  8. while(p) {
  9. if(p->val < x) {
  10. p1->next = p;
  11. p1 = p1->next;
  12. } else {
  13. p2->next = p;
  14. p2 = p2->next;
  15. }
  16. p = p->next;
  17. }
  18. p2->next = NULL;
  19. p1->next = dummy2.next;
  20. return dummy1.next;
  21. }
  22. };