zoukankan      html  css  js  c++  java
  • LeetCode Reverse Linked List (反置链表)

    题意:

      将单恋表反转。

    思路:

      两种方法:迭代和递归。 

      递归 

     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     ListNode* give_me_your_son( ListNode* far, ListNode* son)
    12     {
    13         if(!son)    return far;     //far就是链表尾了
    14         ListNode* tmp=son->next;
    15         son->next=far;
    16         return give_me_your_son( son, tmp);
    17     }
    18 
    19     ListNode* reverseList(ListNode* head) {
    20         if(!head||!head->next)   return head;
    21         return give_me_your_son(0,head);
    22     }
    23 };
    AC代码

    python3

      迭代

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def reverseList(self, head):
     9         """
    10         :type head: ListNode
    11         :rtype: ListNode
    12         """
    13         top=None
    14         while head:
    15              top,head.next,head=head,top,head.next
    16         return top
    AC代码

      递归

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def reverseList(self, head, pre=None):
     9         """
    10         :type head: ListNode
    11         :rtype: ListNode
    12         """
    13         if not head:    return pre
    14         back=head.next
    15         head.next=pre    
    16         return self.reverseList(back, head)
    AC代码
  • 相关阅读:
    用上帝视角来看待组件的设计模式
    npm和package.json那些不为常人所知的小秘密
    四步走查智能硬件异常Case
    PorterDuffXfermode 图像混合技术在漫画APP中的应用
    发布流程进化史
    二叉搜索树的操作集
    02-线性结构1 两个有序链表序列的合并
    07-图6 旅游规划
    树的同构
    线性结构4 Pop Sequence
  • 原文地址:https://www.cnblogs.com/xcw0754/p/4621527.html
Copyright © 2011-2022 走看看