给定一个值,将链表小于该值得结点放到左边,大于该值得放到右边

例如:

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路:分别将值大于小于给定值得结点生成另外两个链表,最后再将这两个链表相连

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* partition(ListNode *&head, int x) {
12         ListNode *list1 = new ListNode(0);
13         ListNode *list2 = new ListNode(0);
14         ListNode *before = list1, *after = list2;
15         while(head)
16         {
17             if(head->val < x)
18             {
19                 before->next = head;
20                 before = before->next;
21             }
22             else
23             {
24                 after->next = head;
25                 after = after->next;
26             }
27             head = head->next;
28         }
29         after->next = NULL;
30         before->next = list2->next;
31         return list1->next;
32     }
33 };

 

相关文章:

  • 2021-06-30
  • 2022-12-23
  • 2021-09-18
  • 2022-01-18
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2021-11-27
猜你喜欢
  • 2021-12-26
  • 2021-05-16
  • 2021-06-28
  • 2022-02-24
  • 2021-06-29
  • 2022-01-05
  • 2022-12-23
相关资源
相似解决方案