本文主要是介绍25期代码随想录算法训练营第三天 | 203.移除链表元素、707.设计链表、206.反转链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 203.移除链表元素
- 707.设计链表
- 206.反转链表
203.移除链表元素
链接
使用虚拟头
# 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 = ListNode(next = head)cur = dummywhile cur.next:if cur.next.val == val:cur.next = cur.next.nextelse:cur = cur.nextreturn dummy.next
707.设计链表
链接
class ListNode:def __init__(self, val, next = None):self.val = valself.next = nextclass MyLinkedList:def __init__(self):self.size = 0self.dummy_head = ListNode(0)def get(self, index: int) -> int:if index < 0 or index >= self.size:return -1cur = self.dummy_head.nextfor i in range(index):cur = cur.nextreturn cur.valdef addAtHead(self, val: int) -> None:self.dummy_head.next = ListNode(val= val, next = self.dummy_head.next)self.size += 1def addAtTail(self, val: int) -> None:cur = self.dummy_headwhile cur.next:cur = cur.nextcur.next = ListNode(val)self.size += 1def addAtIndex(self, index: int, val: int) -> None:if index < 0 or index > self.size:return cur = self.dummy_headfor i in range(index):cur = cur.nextcur.next = ListNode(val = val, next = cur.next)self.size += 1def deleteAtIndex(self, index: int) -> None:if index < 0 or index >= self.size:returncur = self.dummy_headfor i in range(index):cur = cur.nextcur.next = cur.next.nextself.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]:prev = Nonecur = headwhile cur:temp = cur.nextcur.next = prevprev = curcur = tempreturn prev
这篇关于25期代码随想录算法训练营第三天 | 203.移除链表元素、707.设计链表、206.反转链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!