python删除链表中的最小元素_LintCode Python 入门级题目 删除链表元素、整数列表排序...

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 18:54   2079   0

删除链表元素:

循环列表head,判断当前指针pre.next的val是否等于val,

如果是,当前pre重指向pre.next.next,

直至pre.next = Null

# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

# @param head, a ListNode

# @param val, an integer

# @return a ListNode

def removeElements(self, head, val):

# Write your code here

if head is None:

return None

while head.val ==val:

head = head.next

if (head == None):

return None

pre = head

while pre.next is not None:

if pre.next.val == val:

pre.next = pre.next.next

else:

pre = pre.next

return head

整数列表排序:

Python的列表包含sort()方法,可以直接对列表排序并返回排序好之后的列表;

如需逆序排序,先sort后再调用reverse逆序即可。

class Solution:

# @param {int[]} A an integer array

# @return nothing

def sortIntegers(self, A):

return A.sort()

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP