输入n个字符建立单链表,删除表中重复元素并修改计数,实现单链表字符统计
时间: 2023-05-20 18:03:31 浏览: 113
删除单链表中重复结点
4星 · 用户满意度95%
非常感谢您的提问。以下是实现单链表字符统计的代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def create_linked_list(n, chars):
head = Node(chars[0])
current = head
count_dict = {chars[0]: 1}
for i in range(1, n):
if chars[i] in count_dict:
count_dict[chars[i]] += 1
else:
count_dict[chars[i]] = 1
new_node = Node(chars[i])
current.next = new_node
current = new_node
return head, count_dict
def remove_duplicates(head, count_dict):
current = head
while current.next is not None:
if count_dict[current.next.data] > 1:
count_dict[current.next.data] -= 1
current.next = current.next.next
else:
current = current.next
n = int(input("请输入字符个数:"))
chars = input("请输入字符:")
head, count_dict = create_linked_list(n, chars)
remove_duplicates(head, count_dict)
current = head
while current is not None:
print(current.data, count_dict[current.data])
current = current.next
```
希望这个代码能够帮助您解决问题。如果您有任何其他问题,请随时问我。
阅读全文