Leetcode刷题第十五天-链表
203:移除链表元素
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 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]: #虚拟头节点 dummhead=ListNode(next = head) cur=dummhead while cur.next: if(cur.next.val==val): cur.next=cur.next.next else: cur=cur.next return dummhead.next ''' #原链表删除 #如果头节点等于val,删头节点,一直到头节点不是val while head and head.val==val: head=head.next if not head : return head cur=head while cur and cur.next: if(cur.next.val==val): cur.next=cur.next.next else: cur=cur.next return head '''
707:设计链表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class ListNode: def __init__(self,val=0,next=None): self.val=val self.next=next class MyLinkedList: def __init__(self): #虚拟头节点,链表长度为0 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 for i in range(index): cur=cur.next return cur.val def addAtHead(self, val: int) -> None: self.dummyhead.next=ListNode(val,self.dummyhead.next) self.size+=1 def addAtTail(self, val: int) -> None: cur=self.dummyhead 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.dummyhead 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.dummyhead for i in range(index): cur=cur.next cur.next=cur.next.next self.size-=1 def display(self): #返回一个list,便于debug cur=self.dummyhead re=[] while cur: re.append(cur.val) cur=cur.next return re # 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:反转链表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 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]: if not head: return head pre,cur=None,head while cur: tmp=cur.next cur.next=pre pre,cur=cur,tmp return pre