标签:
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
.
Subscribe to see which companies asked this question
/** * 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 || head->next == NULL) return head; ListNode *help = new ListNode(0); help->next = head; ListNode* prev = help, *curr = prev->next; while (curr != NULL) { while (curr != NULL && curr->val < x) { // 找出第一个大于等于x的节点 curr = curr->next; prev = prev->next; } if (curr == NULL) break; ListNode *next = curr->next, *temp = curr; // 注意不是从第一个节点开始 while (next != NULL && next->val >= x) { // 找出第一个小于x的节点 next = next->next; temp = temp->next; } if (next == NULL) break; ListNode* tmp = next->next; next->next = prev->next; // 将小于x的节点插在大于等于x的节点之前 prev->next = next; temp->next = tmp; prev = next; // 前移到下一个节点 curr = prev->next; } return help->next; } };
实际上外层while循环里的第一个while循环可以拿到外层while循环外面,因为后面每次找到的第一个值大于等于x的节点就是curr本身了。
/** * 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 || head->next == NULL) return head; ListNode *help = new ListNode(0); help->next = head; ListNode* prev = help; while (prev->next != NULL && prev->next->val < x) prev = prev->next; ListNode* curr = prev; while (curr->next != NULL) { if (curr->next != NULL && curr->next->val >= x) curr = curr->next; else { ListNode* tmp = curr->next; curr->next = tmp->next; tmp->next = prev->next; prev->next = tmp; prev = prev->next; } } return help->next; } };
解法2:另一种方法就是遍历一遍链表,分别将值小于x和值大于等于x的节点分为两个链表链接起来,然后再将后者链接在前者的末尾就可以了。
[LeetCode]89. Partition List链表划分
标签:
原文地址:http://www.cnblogs.com/aprilcheny/p/4969862.html