【代码随想录day3】203. 移除链表元素,707. 设计链表,206. 反转链表

203. 移除链表元素

虚拟节点dummyhead:

dummy_head = ListNode(next = head)
cur = dummy_head#想要移除节点,需要知道前一个节点!

class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        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

707. 设计链表

class Node(object):#
    def __init__(self, x=0):
        self.val = x
        self.next = None
class MyLinkedList:

    def __init__(self):#初始化
        self.head = Node()
        self._count = 0


    def get(self, index: int) -> int:
        if index < 0 or index >= self._count:
            return -1
        cur = self.head.next
        while index:
            cur = cur.next
            index -= 1
        return cur.val


    def addAtHead(self, val: int) -> None:
        if self._count==0:
            self.head.next = Node(val)
        else:
            node = Node(val)
            node.next = self.head.next
            self.head.next = node  
        self._count += 1


    def addAtTail(self, val: int) -> None:
        cur = self.head
        node = Node(val)
        while cur.next:#找到最后一个节点
            cur = cur.next
        cur.next = node
        self._count += 1


    def addAtIndex(self, index: int, val: int) -> None:
        if index < 0:
            self.addAtHead(val)
            return
        elif index == self._count:
            self.addAtTail(val)
            return
        elif index > self._count:
            return

        node = Node(val)
        cur = self.head#需要前驱节点,所以这里cur指向的是虚拟头节点
        while(index):
            cur = cur.next
            index -= 1
        node.next = cur.next
        cur.next = node
        self._count += 1


    def deleteAtIndex(self, index: int) -> None:
        if index < 0 or index >= self._count:
            return
        cur = self.head
        while(index):
            cur = cur.next
            index -= 1
        cur.next = cur.next.next
        self._count -= 1

206. 反转链表

确定 pre,cur,cur.next

比如1-->2想要实现原地反转。

实现none-->1的反转,变成1-->none
因此初始化时,pre=none。cur = head(此时指向1)
首先需要用tmp记录下一个cur,也就是2,不然1-->2这个链接断了就找不到2了。
实现cur-->pre;
此时的cur就是下一个的pre,因此pre指向cur。此时pre=1
cur指向刚刚记录的下一个cur,此时cur=2

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

        pre = None
        cur = head
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值