203.移除链表元素
首先不看讲解,思想是建立一个哨兵节点dummy用于最后返回新链表的头节点,pre=dummy,cur=head用于维护移除链表元素后链表指针的连续性。
# 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]:
if not head:
return None
dummy = pre = ListNode(0)
dummy.next = head
cur = head
while cur:
if cur.val != val:
cur = cur.next
pre = pre.next
else:
cur = cur.next
pre.next = cur
return dummy.next
题目比较简单,就不看讲解做了,直接下一题。
707.设计链表
没看讲解
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummy = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.dummy.next
for _ in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
if index > self.size:
return
pre = self.dummy
for _ in range(index):
pre = pre.next
pre.next = ListNode(val, pre.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index >= self.size:
return
pre = self.dummy
for _ in range(index):
pre = pre.next
t = pre.next
pre.next = t.next
t.next = None
self.size -= 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]:
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre