输入n个字符建立单链表 删除表中重复元素并修改计数 实现单链表字符统计
时间: 2023-09-04 09:01:47 浏览: 114
首先,我们需要定义一个单链表的数据结构,包括节点的定义和链表的定义。节点定义如下:
```python
class Node:
def __init__(self, data):
self.data = data
self.count = 1
self.next = None
```
链表定义如下:
```python
class LinkedList:
def __init__(self):
self.head = None
```
接下来,我们可以实现建立单链表的函数:
```python
def build_linked_list(n, characters):
linked_list = LinkedList()
for i in range(n):
new_node = Node(characters[i])
if linked_list.head is None:
linked_list.head = new_node
else:
current = linked_list.head
while current.next is not None:
current = current.next
current.next = new_node
return linked_list
```
然后,我们可以实现删除重复元素的函数,并修改节点的计数:
```python
def remove_duplicates(linked_list):
if linked_list.head is None:
return linked_list
current = linked_list.head
while current is not None:
runner = current
while runner.next is not None:
if runner.next.data == current.data:
runner.next = runner.next.next
current.count += 1
else:
runner = runner.next
current = current.next
return linked_list
```
最后,我们可以实现统计单链表中每个字符的个数的函数:
```python
def count_characters(linked_list):
if linked_list.head is None:
return {}
count_dict = {}
current = linked_list.head
while current is not None:
count_dict[current.data] = current.count
current = current.next
return count_dict
```
通过以上的函数,我们就可以建立单链表、删除重复元素并修改计数,并实现单链表字符统计。以下是一个完整的示例代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.count = 1
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def build_linked_list(n, characters):
linked_list = LinkedList()
for i in range(n):
new_node = Node(characters[i])
if linked_list.head is None:
linked_list.head = new_node
else:
current = linked_list.head
while current.next is not None:
current = current.next
current.next = new_node
return linked_list
def remove_duplicates(linked_list):
if linked_list.head is None:
return linked_list
current = linked_list.head
while current is not None:
runner = current
while runner.next is not None:
if runner.next.data == current.data:
runner.next = runner.next.next
current.count += 1
else:
runner = runner.next
current = current.next
return linked_list
def count_characters(linked_list):
if linked_list.head is None:
return {}
count_dict = {}
current = linked_list.head
while current is not None:
count_dict[current.data] = current.count
current = current.next
return count_dict
n = int(input("输入字符个数:"))
characters = []
for i in range(n):
character = input("输入第{}个字符:".format(i+1))
characters.append(character)
linked_list = build_linked_list(n, characters)
linked_list = remove_duplicates(linked_list)
count_dict = count_characters(linked_list)
print(count_dict)
```
这样,我们就能够实现输入n个字符,建立单链表,删除表中重复元素并修改计数,并实现单链表字符统计。