zoukankan      html  css  js  c++  java
  • [LeetCode 206] Reverse Linked List 翻转单链表

    本题要求将给定的单链表翻转,是校招面试手撕代码环节的高频题,能很好地考察对单链表这一最简单数据结构的理解;可以使用迭代和递归两种方法对一个给定的单链表进行翻转,具体实现如下:
     
     1 class Solution {
     2 public:
     3     ListNode* reverseList(ListNode* head) {
     4         return reverseList_iteratively(head);
     5        //return reverseList_recursively(head);//递归方法leetcode超时
     6     }
     7 //迭代 
     8     ListNode* reverseList_iteratively(ListNode* head)
     9     {
    10         ListNode* p = nullptr;
    11         ListNode* w = nullptr;
    12         while(head)
    13         {
    14             p = head->next;
    15             head->next = w;
    16             w = head;
    17             head = p;
    18         }
    19         return w;
    20     }
    21  
    22 //递归
    23      ListNode* reverseList_recursively(ListNode* head)
    24     {
    25         if(head==nullptr||head->next==nullptr)
    26         {
    27             return head;
    28         }
    29         ListNode* h = reverseList_recursively(head->next);
    30         head->next->next=head;//加入反转后的单链表尾部
    31         head = nullptr;
    32         return h;
    33     }
    34 };
  • 相关阅读:
    jquery height
    正则表达式的一点奇怪
    this和call
    ajax views
    史上变态的模块
    在php中有什么用
    localhost访问不了
    $.extend abc
    $.extend
    和人沟通的一个要点
  • 原文地址:https://www.cnblogs.com/wangxf2019/p/12089009.html
Copyright © 2011-2022 走看看