标签:
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的放后面
/** * 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; } };
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52142802