leetcode No86. Partition List

来源:互联网 发布:爬虫怎么找兼职 知乎 编辑:程序博客网 时间:2024/06/03 16:52

Question:

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.

小于x的放前面,大于等于x的放后面

Algorithm:

新建两个链表分别存放小于x的节点和大于等于x的节点。

Accepted Code:

/** * 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* head1=new ListNode(0);     //这样不用在while里面判断是否为头节点        ListNode* head2=new ListNode(0);        ListNode* l1=head1;        ListNode* l2=head2;        ListNode* p=head;        while(p!=NULL)        {            if(p->val<x)            {                l1->next=p;                l1=l1->next;            }            else            {                l2->next=p;                l2=l2->next;            }            p=p->next;        }        l2->next=NULL;        l1->next=head2->next;        return head1->next;    }};



0 0
原创粉丝点击