Day 3 链表1

yuhao0451 / 2023-08-07 / 原文

之前写c的时候就被链表折磨过很多次,现在准备用python 重温一下。

链表的基础知识

相关阅读:https://zhuanlan.zhihu.com/p/60057180

https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzI0NjAxMDU5NA==&action=getalbum&album_id=1928300901752963079&scene=173&from_msgid=2475918898&from_itemidx=1&count=3&nolastread=1#wechat_redirect

Leetcode 203: 

def removeElements(self, head, val) :
    #定义一个辅助节点指向当前头节点
    dummy_head = ListNode(next=head) 
    cur = dummy_head 
    while cur.next :
        if cur.next.val == val:
            cur.next = cur.next.next 
        else:
            cur = cur.next 
    
    return dummy_head.next 

Leetcode 707 

class ListNode(object) :
    def __init__(self, val=0, next=None):
        self.val = val 
        self.next = next 

class MyLinkedList(object) :
    def __init__(self) :
        self.dummy = ListNode() 
        self.size = 0 

    def get(self, index):
        if index < 0 or index >= self.size:
            return -1 
        
        cur = self.dummy.next 
        for i in range(index) :
            cur = cur.next 
        return cur.val 
    
    def addAtHead(self, val):
        return self.addAtIndex(0, val)
    
    def addAtTail(self, val):
        return self.addAtIndex(self.size, val)
    
    def addAtIndex(self, index, val):
        if index < 0 or index > self.size: 
            return 
        
        cur = self.dummy 
        add_node = ListNode(val) 
        for i in range(index):
            cur = cur.next 
        add_node.next = cur.next 
        cur.next = add_node 

        self.size += 1 
    
    def deleteAtIndex(self, index): 
        if index < 0 or index >= self.size :
            return 
        
        cur = self.dummy 
        for i in range(index) :
            cur = cur.next 
        cur.next = cur.next.next 
        self.size -= 1 

    def items(self):
        cur = self.dummy 
        while cur is not None:
            yield cur.val 
            cur = cur.next 
        

Leetcode 206 

def reverseList(self, head) :
    cur = head 
    pre = None 
    while cur : 
        temp = cur.next 
        cur.next = pre 
        pre = cur 
        cur = temp 
    return pre