链表知识总结
分类
-
单链表
-
双链表
-
循环链表(约瑟夫环问题)
链表的定义
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
链表的操作
删除节点
只需要让其中的指向改变即可,O(1)的复杂度
添加节点
直接让指针重新连接即可, O(1)的复杂度
但是查找其中元素的复杂度是O(n)
与数组性能比较
插入/删除 | 查询 | 适用场景 | |
数组 | O(n) | O(1) | 数据量固定,频繁查询,较少删增 |
链表 | O(1) | O(n) | 数据量不固定,频繁删增,较少查询 |
203.移除链表元素
第一想法是,分为两种情况,一个是处理头节点,接着遍历处理,发现顾头不顾尾,总是出bug;看了答案发现虚拟头节点确实好用
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
pre = ListNode() # 初始化链表
pre.next = head
p = pre
while p.next != None:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return pre.next
707.设计链表
我太牛了,竟然自己写出来了
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.size = 0
self.head = ListNode(0)
def get(self, index: int) -> int:
current = self.head
if index < 0 or index >= self.size:
return -1
for _ in range(index+1):
current = current.next
return current.val
def addAtHead(self, val: int) -> None:
p = ListNode(val = val)
p.next = self.head.next
self.head.next = p
self.size += 1
def addAtTail(self, val: int) -> None:
p = ListNode(val = val)
current = self.head
while current.next:
current = current.next
current.next = p
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
new = ListNode(val = val)
current = self.head
if index <= self.size:
for _ in range(index):
current = current.next
new.next = current.next
current.next = new
self.size += 1
def deleteAtIndex(self, index: int) -> None:
current = self.head
if index >= 0 and index < self.size:
for _ in range(index):
current = current.next
current.next = current.next.next
self.size -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
使用虚拟头节点来设计链表
206.反转链表
比较简单,直接做就行
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
newhead = ListNode()
while head:
p = head.next
head.next = newhead.next
newhead.next = head
head = p
return newhead.next