python创建单链表的代码,存放数据1到100
时间: 2023-08-20 10:05:58 浏览: 79
以下是Python创建单链表并存放数据1到100的代码示例:
```python
# 定义单链表节点类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 创建单链表
head = ListNode(0)
cur = head
for i in range(1, 101):
node = ListNode(i)
cur.next = node
cur = node
# 输出单链表
cur = head.next
while cur:
print(cur.val, end=' ')
cur = cur.next
```
运行结果:
```
1 2 3 4 5 ... 96 97 98 99 100
```
相关问题
python往单链表中写入数据
要往单链表中写入数据,你需要先定义链表的节点类,然后实现一个链表类,包含插入节点、删除节点、遍历节点等方法。
下面是一个简单的单链表实现,包含节点类和链表类:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
current = self.head
while current.next:
current = current.next
current.next = Node(data, None)
def insert_at_index(self, index, data):
if index < 0 or index > self.get_length():
raise Exception("Invalid index")
if index == 0:
self.insert_at_beginning(data)
return
current = self.head
current_index = 0
while current:
if current_index == index - 1:
node = Node(data, current.next)
current.next = node
break
current = current.next
current_index += 1
def delete_at_index(self, index):
if index < 0 or index >= self.get_length():
raise Exception("Invalid index")
if index == 0:
self.head = self.head.next
return
current = self.head
current_index = 0
while current:
if current_index == index - 1:
current.next = current.next.next
break
current = current.next
current_index += 1
def get_length(self):
current = self.head
length = 0
while current:
length += 1
current = current.next
return length
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
```
这里实现了插入节点的三种方式:
- insert_at_beginning:在链表头部插入节点
- insert_at_end:在链表尾部插入节点
- insert_at_index:在指定位置插入节点
同时还实现了删除节点和遍历节点的方法。
下面是一个使用示例:
```python
linked_list = LinkedList()
linked_list.insert_at_beginning(2)
linked_list.insert_at_beginning(1)
linked_list.insert_at_end(4)
linked_list.insert_at_index(2, 3)
linked_list.display() # 1 -> 2 -> 3 -> 4 -> None
linked_list.delete_at_index(1)
linked_list.display() # 1 -> 3 -> 4 -> None
```
python单链表代码
答:下面是一个典型的python单链表代码:class Node: def __init__(self,data): self.data=data self.next=Noneclass SLinkedList:def __init__(self): self.head=None def Atbegining(self,data_in): NewNode=Node(data_in) NewNode.next=self.head self.head=NewNode def LListprint(self): lastnode=self.head while lastnode is not None: print(lastnode.data, end=' ') lastnode=lastnode.next print("")list1=SLinkedList()list1.Atbegining("Mon")list1.Atbegining("Tue")list1.Atbegining("Wed")list1.Atbegining("Thu")list1.LListprint()