LeetCode Reverse Linked List (反置链表)

LeetCode Reverse Linked List (反置链表)

题意:

  将单恋表反转。

思路:

  两种方法:迭代和递归。

  递归

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* give_me_your_son( ListNode* far, ListNode* son)
{
if(!son) return far; //far就是链表尾了
ListNode* tmp=son->next;
son->next=far;
return give_me_your_son( son, tmp);
} ListNode* reverseList(ListNode* head) {
if(!head||!head->next) return head;
return give_me_your_son(,head);
}
};

AC代码

python3

  迭代

 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
top=None
while head:
top,head.next,head=head,top,head.next
return top

AC代码

  递归

 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseList(self, head, pre=None):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return pre
back=head.next
head.next=pre
return self.reverseList(back, head)

AC代码

上一篇:string_array.go


下一篇:第十六章——处理锁、阻塞和死锁(3)——使用SQLServer Profiler侦测死锁