python链表输出值转josn
时间: 2023-10-01 22:06:51 浏览: 81
字符串或链表转json
可以使用Python内置的json模块将链表的值转换为json格式。具体实现步骤如下:
1. 定义一个链表类和节点类。
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
```
2. 创建一个链表,并添加一些节点。
```python
linkedList = LinkedList()
linkedList.head = ListNode(1)
secondNode = ListNode(2)
thirdNode = ListNode(3)
linkedList.head.next = secondNode
secondNode.next = thirdNode
```
3. 将链表的值转换为字典类型。
```python
currentNode = linkedList.head
data = {}
index = 0
while currentNode:
data[index] = currentNode.val
index += 1
currentNode = currentNode.next
```
4. 使用json模块将字典转换为json格式。
```python
import json
json_data = json.dumps(data)
print(json_data)
```
完整代码如下:
```python
import json
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
linkedList = LinkedList()
linkedList.head = ListNode(1)
secondNode = ListNode(2)
thirdNode = ListNode(3)
linkedList.head.next = secondNode
secondNode.next = thirdNode
currentNode = linkedList.head
data = {}
index = 0
while currentNode:
data[index] = currentNode.val
index += 1
currentNode = currentNode.next
json_data = json.dumps(data)
print(json_data)
```
输出结果为:
```
{"0": 1, "1": 2, "2": 3}
```
阅读全文