File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * Definition for singly-linked list.
3+ * struct ListNode {
4+ * int val;
5+ * ListNode *next;
6+ * ListNode(int x) : val(x), next(NULL) {}
7+ * };
8+ */
9+ class Solution {
10+ public:
11+ void reorderList (ListNode *head) {
12+ // IMPORTANT: Please reset any member data you declared, as
13+ // the same Solution instance will be reused for each test case.
14+ head = mergeList (head, reverseList (splitList (head)));
15+ return ;
16+ }
17+ private:
18+ ListNode *splitList (ListNode * head) {
19+ if (!head)
20+ return NULL ;
21+ ListNode *fast = head, *slow = head;
22+ while (fast && fast->next ) {
23+ fast = fast->next ->next ;
24+ slow = slow->next ;
25+ }
26+ fast = slow->next ;
27+ slow->next = NULL ;
28+ return fast;
29+ }
30+ ListNode *reverseList (ListNode *head) {
31+ ListNode *pre = NULL , *cur = head, *nxt = NULL ;
32+ while (cur) {
33+ nxt = cur->next ;
34+ cur->next = pre ;
35+ pre = cur;
36+ cur = nxt;
37+ }
38+ return pre ;
39+ }
40+ ListNode *mergeList (ListNode *ha, ListNode *hb) {
41+ ListNode *ret = NULL ;
42+ ListNode **pCur = &ret;
43+ while (ha && hb) {
44+ *pCur = ha;
45+ pCur = &(ha->next );
46+ ha = ha->next ;
47+
48+ *pCur = hb;
49+ pCur = &(hb->next );
50+ hb = hb->next ;
51+ }
52+ *pCur = ha;
53+ return ret;
54+ }
55+ };
You can’t perform that action at this time.
0 commit comments