LeetCode--partition-list(C++)

题目描述:

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,
    Given1->4->3->2->5->2and x = 3,
    return1->2->2->4->3->5.

  • 题目解释:
    本题的意思就是说,给定一个数字,将小于该数字的节点放在链表的前面,将大于等于链表的节点放在后面。

  • 思路分析:本题我们需要定义两个链表,一个用来放节点小于x的值,一个用来放大于等于x的值,最后将两个链表串起来即可,注意:本题不需要我们将链表的节点顺序排序,老铁们可不要画蛇添足哦!

  • 代码实现如下:

/**
 * 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) 
    {
        //判空
        if(head==NULL)
            return NULL;

        ListNode* big=new ListNode(-1);//用来存放节点的值大于x
        ListNode* small =new ListNode(-1);//用来存放节点的值小于x
        ListNode* cur=head;
        ListNode* bignum=big;//大于x值的链表中的节点
        ListNode* smallnum=small;//小于x值的链表中的节点

        //当链表不空时
        while(cur!=NULL)
        {
            if(cur->val < x)//当原链表的值小于x时
            {
                smallnum->next=cur;//注意这里是smallnum->next;因为smallnum为-1
                smallnum=cur;
            }
            else//当原链表的值大于x时
            {
                bignum->next=cur;
                bignum=cur;
            }
            cur=cur->next;
        }

        bignum->next=NULL;//记得将bignum的next置空哦!
        smallnum->next=big->next;//注意这里是小的链表的尾部指向大的链表的头部,因此是big不是bignum哦!
        return small->next;
    }
};

猜你喜欢

转载自blog.csdn.net/cherrydreamsover/article/details/81476347