9名同学分别写下自己的幸运数字,并按数字从小到大存储到链表中。小明想 知道这9名同学的幸运数字有哪几个,并想删除初始链表中重复的幸运数字。请你设计编程算法,帮助小 明实现这一功能。需要注意的是:若头节点或头节点的下一个节点为空,则返回头节点。
时间: 2023-05-18 17:07:33 浏览: 45
以下是一个可能的解决方案:
```python
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def remove_duplicates(head):
if not head or not head.next:
return head
nums = set()
nums.add(head.val)
curr = head
while curr.next:
if curr.next.val in nums:
curr.next = curr.next.next
else:
nums.add(curr.next.val)
curr = curr.next
return head
def get_lucky_numbers(head):
nums = set()
while head:
nums.add(head.val)
head = head.next
return nums
# Example usage:
head = Node(3)
head.next = Node(7)
head.next.next = Node(2)
head.next.next.next = Node(5)
head.next.next.next.next = Node(3)
head.next.next.next.next.next = Node(1)
head.next.next.next.next.next.next = Node(7)
head.next.next.next.next.next.next.next = Node(4)
head.next.next.next.next.next.next.next.next = Node(2)
lucky_nums = get_lucky_numbers(head)
print("Lucky numbers:", lucky_nums)
head = remove_duplicates(head)
lucky_nums = get_lucky_numbers(head)
print("Lucky numbers (after removing duplicates):", lucky_nums)
```
这个算法首先遍历链表,将幸运数字存储到一个集合中,这样就可以快速判断一个数字是否已经出现过了。然后再遍历一次链表,删除重复的数字。最后再遍历一次链表,将所有幸运数字存储到一个集合中,以便输出。