237. Delete Node in a Linked List(Python3)

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

    4 -> 5 -> 1 -> 9

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
             should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
             should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

从链表中,删除指定的节点,但又没有给出前指针,所以先交换当前节点和下一节点的值,然后删除下一节点。

使用链表(Linked List)是一种常见的数据结构,它由一系列节点组成,每个节点包含数据以及指向下一个节点的指针。在管理学生信息时,我们可以用链表来存储学生的信息,例如: 1. 每个节点(StudentNode)代表一个学生,包含学生ID、姓名和分数(score)三个属性。 ```python class StudentNode: def __init__(self, student_id, name, score): self.student_id = student_id self.name = name self.score = score self.next = None # 指向下一个节点 self.prev = None # 如果是在双向链表中,指向前一个节点 ``` 2. 双向链表(Doubly Linked List)则增加了一个prev指针,使得在删除或查找时更高效。 ```python class DoublyLinkedList: def __init__(self): self.head = None self.tail = None # 尾部节点 # 添加节点 def append(self, student_data): new_node = StudentNode(*student_data) if not self.head: self.head = self.tail = new_node else: self.tail.next = new_node new_node.prev = self.tail self.tail = new_node ``` 3. 基本操作包括添加学生、删除学生、查找学生和更新成绩: - `append`方法用于添加学生到链表尾部。 - `delete`方法通过遍历找到指定ID的学生并移除。 - `find`方法通过遍历查找特定ID的学生。 - `update_score`方法在找到学生后修改其分数。 4. 高级操作如获取成绩区间内的学生列表和合并两个链表可以这样设计: - `get_students_in_score_range`方法需要遍历整个链表并检查分数差异。 - `merge_lists`方法需要比较两个链表的头节点,合并它们,同时处理重复的ID问题。 5. 示例代码: ```python def get_students_in_score_range(self, target_score, range=5): ... # 实现计算成绩范围内学生的逻辑 def merge_lists(self, other_list): ... # 实现合并两个链表的逻辑,避免重复 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值