# 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]:
virtualHead = ListNode(-1, head)
pre = virtualHead
cur = virtualHead.next
while cur != None:
if cur.val == val:
cur = cur.next
pre.next = cur
else:
pre = cur
cur = cur.next
return virtualHead.next
707.设计链表
卡bug卡了很久,对于边界条件不够清晰
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummyHead = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.dummyHead.next
n = index
while n > 0:
cur = cur.next
n -= 1
return cur.val
def addAtHead(self, val: int) -> None:
newNode = ListNode(val)
newNode.next = self.dummyHead.next
self.dummyHead.next = newNode
self.size += 1
def addAtTail(self, val: int) -> None:
newNode = ListNode(val, None)
cur = self.dummyHead
while cur.next != None:
cur = cur.next
cur.next = newNode
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
newNode = ListNode(val, None)
n = index
pre = self.dummyHead
while n > 0:
pre = pre.next
n -= 1
newNode.next = pre.next
pre.next = newNode
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
n = index
pre = self.dummyHead
while n > 0:
pre = pre.next
n -= 1
if pre.next != None:
pre.next = pre.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)
# 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]:
vitualHead1 = ListNode(0, head)
vitualHead2 = ListNode()
first = True
while vitualHead1.next != None:
cur = vitualHead1.next
vitualHead1.next = vitualHead1.next.next
cur.next = vitualHead2.next
vitualHead2.next = cur
return vitualHead2.next