学习资料:https://programmercarl.com/链表理论基础.html#链表的类型
可设置虚拟头结点 dummy_head
链表最后指向Null
一个节点包含值和索引
学习记录:
203.移除链表元素(基本ListNode(),cur.next, cur.next.val)
点击查看代码
# 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]:
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next
707.设计链表(找到索引对应值;在第一个元素前插入一个节点;在最后一个元素后面插入一个节点;在索引处插入一个节点;注意链表size变化)
点击查看代码
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummpy_head = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.dummpy_head.next
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.dummpy_head.next = ListNode(val, self.dummpy_head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
cur = self.dummpy_head
while cur.next:
cur = cur.next
cur.next = ListNode(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
cur = self.dummpy_head
for i in range(index):
cur = cur.next
cur.next = ListNode(val, cur.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index<0 or index>=self.size:
return
cur = self.dummpy_head
for i in range(index):
cur=cur.next
cur.next = cur.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]:
cur = head
pre = None
while cur:
temp = cur.next
cur.next = pre # 翻转
pre = cur
cur = temp
return pre
PS:
第一次接触链表,很懵,感觉707题还要反复刷,另外可以用极端条件或画图来更直观判断操作或赋值怎么写
多云转晴,放假期间很难坚持学习啊,幸好有美食支撑(柴火鸡、煲仔饭、泡鸡爪)