码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcod-反转链表

时间:2020-04-18 11:57:28      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:idt   技术   etc   NPU   xpl   迭代   div   reverse   next   

206.逆转链表
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
方法一:迭代
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre, cur = None, head
        while cur:
                pre, cur, cur.next = cur, cur.next, pre
        return pre 
iterative

方法二:递归
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next=None
        return p
recursive

 

24.两两交换链表
Given 1->2->3->4, you should return the list as 2->1->4->3.
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        pre,pre.next = self,head
        while pre.next and pre.next.next:
            a = pre.next
            b = a.next
            a,b.next,b = b,a,b.next
            pre = a 
        return self.next
iterative

技术图片

技术图片

 

 技术图片
 
技术图片
 
141.回环链表
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.

方法一:设置时间暴力循环
方法二:判断是否添加过该元素
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        l = []
        while head != None:
            if head.val in l:
                return True
            l.append(head)
            head=head.next
        return False       
添加进列表
方法三:双步运行
技术图片
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        fir = sec =head
        while fir and sec and sec.next:
           fir = fir.next
           sec = sec.next.next
           if fir == sec:
                return True
        return False     
双步
 
 
 

Leetcod-反转链表

标签:idt   技术   etc   NPU   xpl   迭代   div   reverse   next   

原文地址:https://www.cnblogs.com/ybxw/p/12724747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!