链表part01(23.12.29)
安排:了解一下链接基础,以及链表和数组的区别 ;先独立做题,然后看视频讲解,然后看文章讲解,然后再重新做一遍题,把题目AC,最后整理成今日当天的博客。
- 学习时长:五小时
- 学习内容:自己尝试+pdf说明+视频+力扣题解+自己默写
- 学习感悟:链表比数组难!!
链表理论基础
链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。
与数组适用场景的区别:数组在定义的时候,长度就是固定的,如果想改动数组的长度,就需要重新定义一个新的数组。链表的长度可以是不固定的,并且可以动态增删, 适合数据量不固定,频繁增删,较少查询的场景。
203.移除链表元素
题目链接:力扣题目链接
笔记:两种方法解决,如果不想分类讨论的话就定义一个虚拟头节点
提交代码:
1.直接分类讨论:删除or不删除头节点
# 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]:
while head != None and head.val == val:
head = head.next
cur = head
while cur != None and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
2.虚拟头节点
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummyhead = ListNode()
dummyhead.next = head
cur = dummyhead
while cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummyhead.next
过程中报错:
1.python中没有->next的表示方式,正确写法应当是head.next;python中空应该为None
2.比较值的时候应当用节点的值和target值比,而不是用它本身和值去比较!举个例子head.val == val
3.定义链表的一个新的节点:正确方式是 = ListNode()
707.设计链表
笔记:
1.看了视频同时看了讲义中python的范例,感觉还是直接用范例的方法简洁很多:就是定位直接用for循环,i遍历range(index)
2.range(*) 生成的是[0,1, ..., *-1] ,总是和for搭配使用
3.下标是从0开始算的
提交代码:
class ListNode: #要先定义链表结构体
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self): #链表初始结构
self.dummy_head = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
current = self.dummy_head.next
for i in range(index):
current = current.next
return current.val
def addAtHead(self, val: int) -> None:
self.dummy_head.next = ListNode(val, self.dummy_head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
current = self.dummy_head
while current.next:
current = current.next
current.next = ListNode(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = ListNode(val, current.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = current.next.next
self.size -= 1
过程中报错:
1.要先定义链表结构体
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]:
cur = head
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre