您的位置:首页 > 其它

LeetCode--partition-list

2017-12-31 20:52 441 查看


题目描述

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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//构造两个链表,一个大于全部大于等于x,一个全部小于x,然后将两链表合并
class Solution {
public:
    // 双指针
    ListNode *partition(ListNode *head, int x)
    {
       ListNode *fake1 = new ListNode(0);
       ListNode *fake2 = new ListNode(0);
//构造两个链表的假头结点,起到记录头结点的作用,否则找到合并后的头结点会比较麻烦
       ListNode *p1 = fake1,*p2=fake2;
       while(head)
       {
           if(head->val < x)
           {
               p1->next = head;
               p1 = p1->next;
           }
           else
           {
               p2->next = head;
               p2 = p2->next;
           }
           head = head->next;
       }
       p2->next = nullptr;
       p1->next = fake2->next;
       return fake1->next;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: