2014-03-18 02:27
题目:将一个单链表按照一个值X分为两部分,小于X的部分放在大于等于X的部分之前。
解法:按照值和X的大小,分链表为两条链表,然后连起来成一条。
代码:
1 // 2.4 Write code to partition a linked list around a value x, such that all nodes less than x comes before all nodes greater than or equal to x. 2 #include <cstdio> 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 ListNode *next; 8 ListNode(int x): val(x), next(nullptr) {}; 9 }; 10 11 class Solution { 12 public: 13 ListNode* partitionList(ListNode *head, int x) { 14 if (head == nullptr) { 15 return head; 16 } 17 18 ListNode *h1, *t1, *h2, *t2; 19 ListNode *ptr; 20 21 h1 = t1 = nullptr; 22 h2 = t2 = nullptr; 23 ptr = head; 24 while (ptr != nullptr) { 25 if (ptr->val < x) { 26 if (h1 == nullptr) { 27 h1 = t1 = ptr; 28 } else { 29 t1->next = ptr; 30 t1 = t1->next; 31 } 32 ptr = ptr->next; 33 t1->next = nullptr; 34 } else { 35 if (h2 == nullptr) { 36 h2 = t2 = ptr; 37 } else { 38 t2->next = ptr; 39 t2 = t2->next; 40 } 41 ptr = ptr->next; 42 t2->next = nullptr; 43 } 44 } 45 if (h1 == nullptr) { 46 return h2; 47 } else if (h2 == nullptr) { 48 return h1; 49 } else { 50 t1->next = h2; 51 return h1; 52 } 53 } 54 }; 55 56 int main() 57 { 58 int i; 59 int n, x; 60 int val; 61 struct ListNode *head, *ptr; 62 Solution sol; 63 64 while (scanf("%d", &n) == 1 && n > 0) { 65 // create a linked list 66 ptr = head = nullptr; 67 for (i = 0; i < n; ++i) { 68 scanf("%d", &val); 69 if (head == nullptr) { 70 head = ptr = new ListNode(val); 71 } else { 72 ptr->next = new ListNode(val); 73 ptr = ptr->next; 74 } 75 } 76 77 // partition the list around value x. 78 scanf("%d", &x); 79 head = sol.partitionList(head, x); 80 81 // print the list 82 printf("%d", head->val); 83 ptr = head->next; 84 while (ptr != nullptr) { 85 printf("->%d", ptr->val); 86 ptr = ptr->next; 87 } 88 printf("\n"); 89 90 // delete the list 91 while (head != nullptr) { 92 ptr = head->next; 93 delete head; 94 head = ptr; 95 } 96 } 97 98 return 0; 99 }