insert/delete elements | query | |
array | O(n) | O(1) |
linked list | O(1) | O(n) |
203. Remove Linked List Elements
可以加一个dummy head:用来删除第一个head node。
注意dummy head可以省去对head的单独讨论
cur是临时的pointer,因为不能修改head pointer(最后要返回此值)
创建dummy head的方法:
dummy_head = ListNode(next = head)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next!= None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next
注意要删除的是cur的下一个元素;边界是cur.next不为空
707. Design Linked List
易错点:for addAtIndex n, 题目要求是在第n个node前插入一个node, 所以要保证第n个node是current.next,这样才能在current.next前添加一个node
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList(object):
def __init__(self):
self.dummy_head = ListNode()
self.size=0
def get(self, index):
"""
:type index: int
:rtype: int
"""
if index < 0 or index >=self.size:
return -1
#start from the first node after dummy, 因为是0-indexed.
cur = self.dummy_head.next
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
self.dummy_head.next = ListNode(val,self.dummy_head.next)
self.size+=1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
cur = self.dummy_head
for i in range(self.size):
cur = cur.next
cur.next = ListNode(val)
self.size+=1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index < 0 or index > self.size: #这里是index>self.size(If index equals the length of the linked list, the node will be appended to the end of the linked list),而其他地方是>=
return
cur = self.dummy_head
for i in range(index):
cur = cur.next
cur.next = ListNode(val,cur.next)
self.size+=1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index < 0 or index >=self.size:
return -1
cur = self.dummy_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. Reverse Linked List
双指针法,用pre和cur两个pointer来反转link,反转完pre和cur都向右移动一格,需要用temp来提前记录下一个node
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
pre = None
while (cur!=None):
temp = cur.next
cur.next = pre
pre = cur
cur=temp
return pre
递归写法之后再看