[Leetcode] #86 Partition List

来源:互联网 发布:java软件工程师辛苦么 编辑:程序博客网 时间:2024/06/06 13:01

Discription:

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.

Solution:

ListNode* partition(ListNode* head, int x) {if (!head) return NULL;ListNode *head1 = new ListNode(-1);head1->next = head;head = head1;ListNode *head2 = new ListNode(-1); ListNode *cur = head2;while (head1->next){if (head1->next->val >= x){cur->next = head1->next;cur = cur->next;head1->next = head1->next->next;}elsehead1 = head1->next;}cur->next = NULL;head1->next = head2->next;return head->next;}
ListNode *partition(ListNode *head, int x) {ListNode node1(0), node2(0);ListNode *p1 = &node1, *p2 = &node2;while (head) {if (head->val < x){p1->next = head;p1 = p1->next;}else{p2->next = head;p2 = p2->next;}head = head->next;}p2->next = NULL;p1->next = node2.next;return node1.next;}

0 0
原创粉丝点击