zoukankan      html  css  js  c++  java
  • Leetcode#143 Reorder List

    原题地址

    先把链表分割成前后两半,然后交叉融合

    实践证明,凡是链表相关的题目,都应该当成工程类题目做,局部变量、功能函数什么的随便整,代码长了没关系,关键是清楚,不容易出错。

    代码:

     1 ListNode *reverseList(ListNode *head) {
     2   if (!head) return head;
     3         
     4   ListNode *prev = head;
     5   head = head->next;
     6   prev->next = NULL;
     7   while (head) {
     8     ListNode *next = head->next;
     9     head->next = prev;
    10     prev = head;
    11     head = next;
    12   }
    13         
    14   return prev;
    15 }
    16     
    17 ListNode *mergeList(ListNode *head1, ListNode *head2) {
    18   ListNode *next1, *next2;
    19   ListNode *head = head1;
    20         
    21   while (head1 && head2) {
    22     next1 = head1->next;
    23     next2 = head2->next;
    24     head1->next = head2;
    25     if (next1)
    26       head2->next = next1;
    27     head1 = next1;
    28     head2 = next2;
    29   }
    30         
    31   return head;
    32 }
    33 
    34 void reorderList(ListNode *head) {
    35   if (!head)
    36     return;
    37             
    38   ListNode *fast = head;
    39   ListNode *slow = head;
    40   while (fast && fast->next) {
    41     fast = fast->next->next;
    42     slow = slow->next;
    43   }
    44         
    45   ListNode *head1 = head;
    46   ListNode *head2 = reverseList(slow->next);
    47   slow->next = NULL;
    48   mergeList(head1, head2);
    49 }
  • 相关阅读:
    Data Wrangling文摘:Non-tidy-data
    Data Wrangling文摘:Tideness
    Python文摘:Mixin 2
    Python文摘:Mixin
    Python文摘:Python with Context Managers
    Python学习笔记11
    SQL学习笔记9
    SQL学习笔记8
    SQL学习笔记7
    Python学习笔记10:内建结构
  • 原文地址:https://www.cnblogs.com/boring09/p/4257133.html
Copyright © 2011-2022 走看看