The answer is not easy. Please accept it.
can be implemented as follows, the code is for reference only:
- Defines a structure of linked list nodes to hold student information, including language, English and three grades.
class ListNode:
def __init__(self, name, score_chinese, score_math, score_english):
self.name = name
self.score_chinese = score_chinese
self.score_math = score_math
self.score_english = score_english
self.next = None
- Create two linked lists, one to hold all student data and one to hold the failed student data.
all_students = ListNode("dummy", -1, -1, -1)
fail_students = ListNode("dummy", -1, -1, -1)
Where, a sentinel node(dummy) is used as the header of the linked list to facilitate the subsequent operation.
- Inserts student data into the all_students linked list. Suppose the data already exists in a two-dimensional list, and the first element of each sublist is the student's name, the second element is the language score, the third element is the math score, and the fourth element is the English score.
data = [["张三", 80, 75, 70], ["李四", 90, 55, 65], ["王五", 50, 60, 70]]
for row in data:
name = row[0]
score_chinese = row[1]
score_math = row[2]
score_english = row[3]
node = ListNode(name, score_chinese, score_math, score_english)
node.next = all_students.next
all_students.next = node
- traverses the all_students linked list, inserting the failed student data into the fail_students linked list.
p = all_students.next
while p is not None:
if p.score_chinese < 60 or p.score_math < 60 or p.score_english < 60:
node = ListNode(p.name, p.score_chinese, p.score_math, p.score_english)
node.next = fail_students.next
fail_students.next = node
p = p.next
Finally, walk through the fail_students linked list, printing all the students who failed.
p = fail_students.next
while p is not None:
print(p.name, p.score_chinese, p.score_math, p.score_english)
p = p.next