题解 | #划分链表#

划分链表

http://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f

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

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    ListNode* partition(ListNode* head, int x) {
        // write code here
        ListNode* pre = new ListNode(0);
        ListNode* post = new ListNode(0);
        
        ListNode* a = pre;
        ListNode* b = post;
        ListNode* cur = head;
        while(cur != nullptr){
            if(cur->val < x){
                a->next = cur;
                a = cur;
                cur = cur->next;
            }
            else{
                b->next = cur;
                b = cur;
                cur = cur->next;
            }
        }
        
        a->next = post->next;
        b->next = nullptr;
        return pre->next;
    }
};
全部评论

相关推荐

06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务