数组与链表
1.数组:
数组的时间复杂度:
2.链表
插入:
删除:
链表插入与删除速度比数组快,但是查询比数组慢。数据结构没有最好,只有最适合。
双链表:
链表的时间复杂度:
3.Leetcode 代码实战
3.1 Reverse Linked List](反转链表)
206. Reverse Linked List
leetcode代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head) :
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
jupyter代码:
# 实现一个链表类,只有一个值val和一个指向下一个节点的next'指针'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#核心代码
class Solution:
def reverseList(self, head) :
cur, prev = head, None
while cur:
nex = cur.next
cur.next = prev
prev = cur
cur = nex
# cur.next, prev, cur = prev, cur, cur.next
return prev
#测试用例,构造 1->2->3->4 链表,返回 4->3->2->1
if __name__ == '__main__':
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
a.next = b
b.next = c
c.next = d
c1 = Solution()
l = c1.reverseList(a)
while l.next:
print(l.val,end =' ')
l = l.next
print(l.val)
# print([l.val, l.next.val,l.next.next.val, l.next.next.next.val])
结果:
jupyter代码原理:
leetcode代码原理:
3.2 Swap Nodes in Pairs(两两反转)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head) :
pre ,pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
print(self.next.val,self.next.next.val)
return self.next
结果:
原理:
3.3 linked-list-cycle(探测链表环)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast=slow=head
while fast and slow and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
结果: