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
.
基本思路:
1. 设置两个临时链表
2. 将小于x的节点,挂到一个链表上。将大于等于的节点,挂到另一个链表上。
3. 串接两个链表。将后一个链表的头部,挂以前一个链表的尾部。
所犯的错误:
初次提交时,漏写了
p2->next = 0;
提交后,报告运行时间超出。
/** * 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 h1(0); ListNode h2(0); ListNode *p1 = &h1; ListNode *p2 = &h2; while (head) { if (head->val < x) { p1->next = head; p1 = p1->next; } else { p2->next = head; p2 = p2->next; } head = head->next; } p1->next = h2.next; p2->next = 0; // 此句漏写,将会在单链表中产生环。 return h1.next; } };
在leetcode讨论组中,有一个更简洁的写法。
https://leetcode.com/discuss/21032/very-concise-one-pass-solution
ListNode *partition(ListNode *head, int x) { ListNode node1(0), node2(0); ListNode *p1 = &node1, *p2 = &node2; while (head) { if (head->val < x) p1 = p1->next = head; else p2 = p2->next = head; head = head->next; } p2->next = NULL; p1->next = node2.next; return node1.next; }
使用连续赋值,将两句写成了一句。
时间: 2024-09-29 03:57:49