首页 > 代码库 > leetcode - Partition List
leetcode - Partition List
题目:Partition List
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小的放在前面,其余的放在后面
个人思路:
1、根据序列的第一个结点是否小于x分成两种情况,若小于x,则将整个序列看成两部分,第一部分是小于x的序列,第二部分是还未遍历过的,当我们去遍历第二部分时,将第二部分的小于x的结点放到第一部分的尾部,直到第二部分遍历完成即可,这时的第二部分就是大等于x的序列,若大等于x,则第一部分是大等于x的序列,遍历第二部分时将大等于x的结点放到第一部分尾部,遍历结束时再将这两部分颠倒一下即可
2、注意一下边界情况即可
代码:
1 /* 2 #include <stddef.h> 3 4 struct ListNode 5 { 6 int val; 7 ListNode *next; 8 ListNode(int x) : val(x), next(NULL) {}; 9 }; 10 */ 11 class Solution 12 { 13 public: 14 ListNode *partition(ListNode *head, int x) 15 { 16 if (!head) 17 { 18 return NULL; 19 } 20 21 bool flag; //第一个结点的值是否小于x 22 23 if (head->val < x) 24 { 25 flag = true; 26 } 27 else 28 { 29 flag = false; 30 } 31 32 if (flag) 33 { 34 ListNode *less = head; 35 ListNode *before = head; 36 ListNode *current = head->next; 37 38 while (current) 39 { 40 if (current->val < x) 41 { 42 if (before != less) 43 { 44 before->next = current->next; 45 current->next = less->next; 46 less->next = current; 47 less = less->next; 48 current = before->next; 49 } 50 else 51 { 52 less = less->next; 53 before = before->next; 54 current = current->next; 55 } 56 } 57 else 58 { 59 before = before->next; 60 current = current->next; 61 } 62 } 63 } 64 else 65 { 66 ListNode *greater = head; 67 ListNode *before = head; 68 ListNode *current = head->next; 69 70 while (current) 71 { 72 if (current->val >= x) 73 { 74 if (before != greater) 75 { 76 before->next = current->next; 77 current->next = greater->next; 78 greater->next = current; 79 greater = greater->next; 80 current = before->next; 81 } 82 else 83 { 84 greater = greater->next; 85 before = before->next; 86 current = current->next; 87 } 88 } 89 else 90 { 91 before = before->next; 92 current = current->next; 93 } 94 } 95 96 if (before != greater) //表明该链表中存在小于x的结点,将它们放到大等于x结点的前面 97 { 98 before->next = head; 99 head = greater->next;100 greater->next = NULL;101 }102 }103 104 return head;105 }106 };
在网上还看到另一个思路,需要消耗O(n)的内存,自己创建两个链表,分别存放小于x和大等于x的结点,遍历一遍原来的序列后,将这两个链表合并一下即可
leetcode - Partition List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。