lintcode 96. 链表划分

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。你应该保留两部分内链表节点原有的相对顺序。

样例
样例 1:

输入: list = null, x = 0
输出: null	
样例解释: 空链表本身满足要求
样例 2:

输入: list = 1->4->3->2->5->2->null, x = 3
输出: 1->2->2->4->3->5->null	
样例解释: 要保持原有的相对顺序。
/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The first node of linked list
     * @param x: An integer
     * @return: A ListNode
     */
    ListNode * partition(ListNode * head, int x) {
        // write your code here
        if(head==NULL) return head;
        ListNode *small=new ListNode(0);
        ListNode *big=new ListNode(0);
        ListNode *ps=small;
        ListNode *pb=big;
        while(head)
        {
            if(head->val<x) {
                ps->next=head;
                head=head->next;
                ps=ps->next;
                ps->next=NULL;
            }
            else{
                pb->next=head;
                head=head->next;
                pb=pb->next;
                pb->next=NULL;
            }
        }
        ps->next=big->next;
        return small->next;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103940454