zoukankan      html  css  js  c++  java
  • 【LeetCode】成对交换节点

    e.g. 给定链表 1->2->3->4,返回 2->1->4->3 的头节点。

    我写了个常见的从头节点遍历,少量的奇数个或偶数个数据都能成功重新排列。但链表过长时结果显示 Time Limit Exceeded 

     1 ListNode* swapPairs(ListNode* head) {
     2     ListNode *p = head, *q, *pre;
     3     while (p) {
     4         if (q = p->next) {
     5             if (p == head)  head = q;
     6             p->next = q->next;
     7             q->next = p;
     8             if (pre)    pre->next = q;
     9         }
    10         pre = p;
    11         p = p->next;
    12     }
    13     return head;
    14 }

    看到有一个答案使用二级指针,忘了这种方法了!

    pp 从指向 head 指针到指向所有 next 指针遍历下去,p 指向 *pp 表示指向当前结点,q 指向 p 的下一个节点。

     1 ListNode* swapPairs(ListNode* head) {
     2     ListNode **pp = &head, *p, *q;
     3     while ((p = *pp) && (q = p->next)) {
     4         p->next = q->next;
     5         q->next = p;
     6         *pp = q;
     7         pp = &(p->next);
     8     }
     9     return head;
    10 }

    看到有些答案标题写使用递归,想了下,把两种思路都 DIY 为递归方法,Accepted了。

     1 ListNode* swapPairs(ListNode* head) {
     2     if (!head || !head->next)  return head;
     3     ListNode *p = head, *q = p->next;
     4     if (!q->next)
     5         p->next = NULL;
     6     else
     7         p->next = swapPairs(q->next);
     8     q->next = p;
     9     return q;
    10 }
    1 ListNode* swapPairs(ListNode* head) {
    2     if (!head || !head->next)    return head;
    3     ListNode **pp = &head, *q = (*pp)->next;
    4     (*pp)->next = swapPairs(q->next);
    5     q->next = *pp;
    6     pp = &q;
    7     return *pp;
    8 }

    可以看到二级指针代码量确实会少一点,而且使用递归代替迭代有时能减少时间。

    但答案这种递归方法最为简单,只用定义一个指针。改为使用二级指针目测无法实现。

    1 ListNode* swapPairs(ListNode* head) {
    2     if(!head || !head->next)    return head;
    3     ListNode *next = head->next;
    4     head->next = swapPairs(next->next);
    5     next->next = head;
    6     return next;
    7 }
  • 相关阅读:
    node 中的 异步地狱回调
    node 同步和异步的概念
    【Node】File System
    阅读《软技能:代码之外的生存指南》读书笔记
    整理前端学习资料以便日后查看
    【css】单选框和复选框文字垂直居中问题
    [CSS]图片与文字对齐问题--摘自张鑫旭博客
    百度首页换一换功能js实现
    个人加分项
    开课第十五周周总结
  • 原文地址:https://www.cnblogs.com/wayne793377164/p/7146990.html
Copyright © 2011-2022 走看看