链表划分

来源:互联网 发布:腾讯云与阿里云 编辑:程序博客网 时间:2024/05/22 11:32

问题描述:

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。

样例

给定链表 1->4->3->2->5->2->null,并且 x=3

返回 1->2->2->4->3->5->null

解题思路:

新建两个链表,比较每个节点与给定值的大小关系,放入两个两表之一,最后再合成一个链表。

代码:

/**

 * Definition of ListNode
 * 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) {
        if (head == NULL) {
            return NULL;
        }
        ListNode *leftDummy = new ListNode(0);
        ListNode *rightDummy = new ListNode(0);
        ListNode *left = leftDummy, *right = rightDummy;
        while (head != NULL) {
            if (head->val < x) {
                left->next = head;
                left = head;
            } else {
                right->next = head;
                right = head;
            }
            head = head->next;
        }
             right->next = NULL;
        left->next = rightDummy->next;
        return leftDummy->next;
    // write your code here
    }
};

感想:

建两个链表来解决此问题的方法可用到其他方面。

0 0
原创粉丝点击