以给定值为基分割链表

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

例如:

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 };

 

转载于:https://www.cnblogs.com/zhangbaochong/p/5158479.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值