首页 > 其他 > 详细

LeetCode 面试题 02.04. 分割链表

时间:2020-03-03 09:57:41      阅读:51      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/partition-list-lcci/ 

编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。

示例:

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

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* partition(struct ListNode* head, int x){
10     if(head==NULL||head->next==NULL) return head;
11     struct ListNode *q=head,*p=head;
12     while(q){
13         if(q->val<x){
14             int tmp=q->val;
15             q->val=p->val;
16             p->val=tmp;
17             p=p->next;
18         }
19         q=q->next;
20     }
21     return head;
22 }

 

LeetCode 面试题 02.04. 分割链表

原文:https://www.cnblogs.com/shixinzei/p/12400468.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!