首页 > 代码库 > leetcode 刷题之路 82 Partition List

leetcode 刷题之路 82 Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.

将链表中值小于某个数的节点移动到前半部分,/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) 
    {
        ListNode* dummyHead1=new ListNode(0);
        ListNode* dummyHead2=new ListNode(0);
        ListNode *p=dummyHead1,*q=dummyHead2;
        while(head!=NULL)
        {
            if(head->val<x)
            {
                p->next=head;
                head=head->next;
                p=p->next;
            }
            else
            {
                q->next=head;
                head=head->next;
                q=q->next;
            }
        }
        p->next=NULL;
        q->next=NULL;
        p->next=dummyHead2->next;
        p=dummyHead1->next;
        delete dummyHead1;
        delete dummyHead2;
        return p;
    }
划分链表,使得值小于某个数的节点都位于链表的前半部分,大于等于这个数的节点位于链表后半部分,且每部分的节点相对顺序保持不变。

方便起见,使用两个辅助头结点dummyHead1,dummyHead2作为两个链表的头结点,分别存储值小于给定数据的节点和值大于等于给定数据的节点,遍历原链表,根据链表节点值大小比较结果将节点移动到这两个辅助头结点表示的某一个链表中,最后再将两个链表头尾相连拼接即可。

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) 
    {
        ListNode* dummyHead1=new ListNode(0);
        ListNode* dummyHead2=new ListNode(0);
        ListNode *p=dummyHead1,*q=dummyHead2;
        while(head!=NULL)
        {
            if(head->val<x)
            {
                p->next=head;
                head=head->next;
                p=p->next;
            }
            else
            {
                q->next=head;
                head=head->next;
                q=q->next;
            }
        }
        p->next=NULL;
        q->next=NULL;
        p->next=dummyHead2->next;
        p=dummyHead1->next;
        delete dummyHead1;
        delete dummyHead2;
        return p;
    }
};