编写一个程序,删除单链表中数据域重复的节点
时间: 2024-05-14 14:15:15 浏览: 79
数据结构实验,单链表的实现.rar_单链表_数据结构实验
这里给出一个Python的实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def delete_duplicate(head):
if head is None:
return
current = 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
else:
runner = runner.next
current = current.next
# 测试
head = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(2)
n5 = Node(4)
head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
delete_duplicate(head)
current = head
while current is not None:
print(current.data)
current = current.next
```
输出结果为:
```
1
2
3
4
```
思路解析:
这个问题可以用两个指针current和runner来解决。current指向当前节点,runner从current开始向后遍历,如果发现runner指向的节点的数据和current指向的节点的数据相同,就将runner指向的节点删除;否则,runner继续向后遍历。当runner遍历完链表后,current才向后移动一位,继续进行上述操作,直到current遍历完链表为止。这样就能够删除单链表中数据域重复的节点了。
阅读全文