将各个城市的信息存入一个带头结点的单链表。结点中的城市信息包括城市名、位置坐标。要求能够利用城市名和位置坐标进行有关查找、插入、删除更新等操作。 (1)输入城市信息,建立江苏省城市链表 (2)查看城市
时间: 2024-10-09 10:10:38 浏览: 29
创建一个带头节点的单链表结构来存储城市信息,每个节点包含城市名和位置坐标,可以按照以下步骤进行:
1. 定义一个CityNode类,它有两个属性:city_name(字符串类型代表城市名)和coordinate(坐标类型,例如Point或元组),以及两个指向前一个节点和下一个节点的引用。
```python
class CityNode:
def __init__(self, city_name, coordinate):
self.city_name = city_name
self.coordinate = coordinate
self.next = None
self.prev = None
class CityList:
def __init__(self):
self.head = None
```
2. 实现插入城市的功能,比如添加江苏省的城市到链表中:
```python
def insert_city(self, city_name, coordinate):
new_node = CityNode(city_name, coordinate)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
```
3. 查看某个特定城市的操作,可以通过遍历链表寻找指定的城市名:
```python
def search_city_by_name(self, city_name):
current = self.head
while current:
if current.city_name == city_name:
return current
current = current.next
return None # 如果没找到则返回None
def search_city_by_coordinate(self, coordinate):
current = self.head
while current:
if current.coordinate == coordinate:
return current
current = current.next
return None
```
4. 删除城市可以根据名称或坐标进行:
```python
def delete_city_by_name(self, city_name):
current = self.head
prev = None
while current:
if current.city_name == city_name:
if prev is None:
self.head = current.next
if self.head:
self.head.prev = None
else:
prev.next = current.next
if current.next:
current.next.prev = prev
break
prev = current
current = current.next
def delete_city_by_coordinate(self, coordinate):
current = self.head
prev = None
while current:
if current.coordinate == coordinate:
if prev is None:
self.head = current.next
if self.head:
self.head.prev = None
else:
prev.next = current.next
if current.next:
current.next.prev = prev
break
prev = current
current = current.next
```
5. 更新城市信息也是类似的过程,只需找到对应的节点然后修改其属性即可。
阅读全文