python_2_leet_链表操作

0 python 链表操作

# 定义节点
class Node():
    # 初始化节点
    def __init__(self, value):
        # value存放数据元素
        self.value = value
        # next是指向下一个元素,初始化指向空
        self.next = None


# 定义链表(单向链表)
class LinkList():
    # 初始化
    def __init__(self):
        self._head = None

    # 判断链表是否为空
    def is_empty(self):
        return self._head is None

    # 链表长度
    def length(self):
        count = 0
        current = self._head  # 当前节点
        while current is not None:
            count = count + 1
            current = current.next
        return count

    # 遍历链表
    def items(self):
        current = self._head
        while current is not None:
            yield current.value
            current = current.next

    # 头部添加元素
    def insert_head(self, value):
        new_node = Node(value)
        new_node.next = self._head
        self._head = new_node

    # 尾部添加元素
    def append(self, value):
        new_node = Node(value)
        if self.is_empty():
            self._head = new_node
        else:
            current = self._head
            while current.next is not None:
                current = current.next
            current.next = new_node

    # 指定位置插入元素
    def insert_index(self, index, value):
        if index <= 1:
            self.insert_head(value)
        elif index > (self.length()):
            self.append(value)
        else:
            new_node = Node(value)
            current = self._head
            for i in range(index):
                current = current.next
            new_node.next = current
            current.next = new_node

    # 删除节点
    def remove(self, value):
        current = self._head
        pre = None
        while current is not None:
            if current.value == value:
                if not pre:
                    self._head = current.next
                else:
                    pre.next = current.next
                return True
            else:
                pre = current
                current = current.next

    # 查找元素是否存在
    def find(self, value):
        if self.is_empty() is None:
            return False
        else:
            current = self._head
            while (current.value != value) and (current.next != None):
                current = current.next
            if current.value == value:
                return True
            else:
                return False

1 python 反转链表

def func1(head):
    p = head
    q = head.next
    p.next = None
    while q:
        r = q.next
        q.next = p
        p = q
        q = r
    return p

l1 = linklist()
l1.insert(1)
l1.insert(5)
l1.insert(6)
l1.root = func1(l1.root)
l1.bianli()

在这里插入图片描述
翻转成功,leetcode却不行?
在这里插入图片描述

2 链表两数相加(14分钟)

2.1 测试逆向取数

l1 = LinkList()  # 456
l1.append(4)
l1.append(5)
l1.append(6)
l2 = LinkList()  # 12
l2.append(1)
l2.append(2)


# 654+12=666
num = 0
tmp = 1
m = l1.items()
for i in range(l1.length()):
    num = num + next(m) * tmp
    tmp = tmp * 10
print(num)

结果为654,实现逆向拿出数字
2.2 测试:两数相加

def get_num(length,x):
    num = 0
    tmp = 1
    for i in range(length):
        num = num + next(x) * tmp
        tmp = tmp * 10
    return num
num1 = get_num(l1.length(),l1.items())
num2 = get_num(l2.length(),l2.items())
print(num1)
print(num2)
print(num1+num2)

2.3 实现链表返回加数

l2._head = None
current = l2._head
num = 789
flag = 0
for i in str(num):
    if flag == 0:
        new_node = Node(value=int(i))
        l2._head = new_node
        flag = 1
    else:
        new_node = Node(value=int(i))
        current = l2._head
        while current.next is not None:
            current = current.next
        current.next = new_node
l2.items()

在这里插入图片描述

2.4 leec运行

# 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 length(self,head):         # 算链表长度 
        current = head
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        return count
    
    def items(self,head):
        current = head
        while current is not None:
            yield current.val
            current = current.next

    def get_number(self,length,x):     # 取数字
        num = 0            # 累加
        tmp = 1            # 累乘
        for i in range(length):
            num = num + next(x) * tmp
            tmp = tmp * 10
        return num

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        num1 = get_number(l1.length(),l1.items())
        num2 = get_number(l2.length(),l2.items())
        return num1+num2

运行不起来,难道这里面不能用函数吗????

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
               # 算链表长度 
        current = l1
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l1_length = count

        current = l2
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l2_length = count
    
        q = l1
        p = l2

        num1 = 0            # 累加
        tmp = 1            # 累乘
        for i in range(l1_length):
            num1 = num1 + q.val * tmp
            q = q.next
            tmp = tmp * 10
        tmp = 1
        num2 = 0
        for i in range(l2_length):
            num2 = num2 + p.val * tmp
            p = p.next
            tmp = tmp * 10
        num = num1 + num2

        l2 = None
        current = l2
        flag = 0
        for i in str(num):
            if flag == 0:
                new_node = ListNode(value=int(i))
                l2._head = new_node
                flag = 1
            else:
                new_node = ListNode(value=int(i))
                current = l2
                while current.next is not None:
                    current = current.next
                current.next = new_node
        return l2

运行不起来,不能使用head重新建立链表?
答案是没有用人家的规则

2.5 修改后下面代码可以运行

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
               # 算链表长度 
        current = l1
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l1_length = count

        current = l2
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l2_length = count
    
        q = l1
        p = l2

        num1 = 0            # 累加
        tmp = 1            # 累乘
        for i in range(l1_length):
            num1 = num1 + q.val * tmp
            q = q.next
            tmp = tmp * 10
        tmp = 1
        num2 = 0
        for i in range(l2_length):
            num2 = num2 + p.val * tmp
            p = p.next
            tmp = tmp * 10
        num = num1 + num2

        l2 = None
        current = l2
        flag = 0
        for i in str(num):
            if flag == 0:
                new_node = ListNode(val=int(i))
                l2 = new_node
                flag = 1
            else:
                new_node = ListNode(val=int(i))
                current = l2
                while current.next is not None:
                    current = current.next
                current.next = new_node
        return l2

2.6 通过

# 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 addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
               # 算链表长度 
        current = l1
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l1_length = count

        current = l2
        count = 0
        while current is not None:
            count = count + 1
            current = current.next
        l2_length = count
    
        q = l1
        p = l2

        num1 = 0           # 累加
        tmp = 1            # 累乘
        for i in range(l1_length):
            num1 = num1 + q.val * tmp
            q = q.next
            tmp = tmp * 10
        tmp = 1
        num2 = 0
        for i in range(l2_length):
            num2 = num2 + p.val * tmp
            p = p.next
            tmp = tmp * 10
        num = num1 + num2               # num为807

        l2 = None
        current = l2
        flag = 0
        for i in str(num):
            new_node = ListNode(val=int(i))
            if flag == 0:
                l2 = new_node
                flag = 1
            else:
                current = new_node
                current.next = l2
                l2 = current
        return l2

在这里插入图片描述

3 链表,删除指定数值的值

def remove(head,num):
    while(head is not None):   # 万一头部要删数值,要找到第一个不需要删除的数值
        if(head.value != num):  
            break               # 跳出循环
        head = head.next
    pre = head
    cur = head
    while(cur is not None):
        if cur.value == num:
            pre.next = cur.next  # 指针绕过num节点
        else:
            pre = cur
        cur = cur.next
    return head

4 栈、队列

https://zhuanlan.zhihu.com/p/151275111

4.1 双向链表实现队列

4.1.2 带有头尾指针的头插法

linklist = LinkList()
# val = input()
def addHead(value):
    new_node = Node(value)
    if linklist.is_empty():
        linklist._head = new_node            # 头指针指向新结点
        head = new_node                      # 自己设置的指针指向新节点,这就是节点类型 
        tail = new_node
    else:
        new_node.next = linklist._head
        linklist._head.prev = new_node
        linklist._head = new_node
addHead(1)
addHead(2)
linklist.travel()                 # 因为是头插法,所以遍历出来是2 1

4.1.2 带有头尾指针的尾插法

记住尾指针创建地方在

class LinkList:
    def __init__(self):
        self._head = None
        self._tail = None           # 尾指针
def addBootom(value):               # 尾部增加节点
    new_node = Node(value)
    if linklist.is_empty():
        linklist._head = new_node
        linklist._tail = new_node            # 尾指针指向新节点
    else:
        linklist._tail.next = new_node      # 尾指针指向的节点的下一个指向新节点
        new_node.prev = linklist._tail
        linklist._tail = new_node           # 尾指针指向新节点

可以插入数据

4.1.3 从头部取出元素

def getHead():
    if linklist.is_empty():       # 如果链表是空
        return None
    cur = linklist._head          # cur指向当前头指针所指向的位置
    if linklist._head == linklist._tail: # 头指针和尾指针指向节点一样
        linklist._head = None            # 头指针指向空,尾指针也指向空
        linklist._tail = None
    else:
        num = linklist._head.value
        linklist._head = linklist._head.next   # 头指针指向下一个节点
        linklist._head.prev = None
        print(num)

4.1.4 从尾部取出元素

def getBottom():
    if linklist.is_empty():
        return None
    cur = linklist._tail
    if linklist._tail == linklist._head:
        linklist._head = None
        linklist._tail = None
    else:
        linklist._tail = linklist._tail.prev
        linklist._tail.next = None
    return cur.value

4.2 双向链表队列实现整体代码

class Queue:
    # def popHead(self):     只允许头进尾出
    #     num = getHead()
    #     print(num)

    def popBottom(self):
        num = getBottom()
        print(num)

    def pushHead(self,value):
        addHead(value)

    # def pushBottom(self,value):
    #     addBottom(value)
    #

queue1 = Queue()
queue1.pushHead(1)
queue1.pushHead(2)
queue1.pushHead(3)
queue1.popBottom()

4.3 双向链表栈实现

class Stack:             # 只允许头进头出
    def pushstack(self,value):
        addHead(value)
    def popstack(self):
        num = getHead()
        print(num)

stack = Stack()
stack.pushstack(1)
stack.pushstack(2)
stack.pushstack(3)
stack.popstack()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
探险家小扣的行动轨迹,都将保存在记录仪中。expeditions[i] 表示小扣第 i 次探险记录,用一个字符串数组表示。其中的每个「营地」由大小写字母组成,通过子串 -> 连接。例:"Leet->code->Campsite",表示到访了 "Leet"、"code"、"Campsite" 三个营地。expeditions[0] 包含了初始小扣已知的所有营地;对于之后的第 i 次探险(即 expeditions[i] 且 i > 0),如果记录中包含了之前均没出现的营地,则表示小扣 新发现 的营地。 请你找出小扣发现新营地最多且索引最小的那次探险,并返回对应的记录索引。如果所有探险记录都没有发现新的营地,返回 -1。注意: 大小写不同的营地视为不同的营地; 营地的名称长度均大于 0。用python实现。给你几个例子:示例 1: 输入:expeditions = ["leet->code","leet->code->Campsite->Leet","leet->code->leet->courier"] 输出:1 解释: 初始已知的所有营地为 "leet" 和 "code" 第 1 次,到访了 "leet"、"code"、"Campsite"、"Leet",新发现营地 2 处:"Campsite"、"Leet" 第 2 次,到访了 "leet"、"code"、"courier",新发现营地 1 处:"courier" 第 1 次探险发现的新营地数量最多,因此返回 1。示例 2: 输入:expeditions = ["Alice->Dex","","Dex"] 输出:-1 解释: 初始已知的所有营地为 "Alice" 和 "Dex" 第 1 次,未到访任何营地; 第 2 次,到访了 "Dex",未新发现营地; 因为两次探险均未发现新的营地,返回 -1
04-23
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值