python如何把一个新的链表赋给链表里的链表
时间: 2024-01-04 08:17:59 浏览: 119
可以通过遍历链表找到最后一个节点,然后将新链表的头节点赋值给最后一个节点的next指针即可。具体实现方法如下所示:
```python
# 定义链表节点类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 定义链表类
class LinkedList:
def __init__(self):
self.head = None
# 在链表尾部添加节点
def addAtTail(self, val: int) -> None:
node = ListNode(val)
if not self.head:
self.head = node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
# 定义一个新链表
new_list = LinkedList()
new_list.addAtTail(1)
new_list.addAtTail(2)
new_list.addAtTail(3)
# 定义一个原链表
old_list = LinkedList()
old_list.addAtTail(4)
old_list.addAtTail(5)
# 将新链表赋给原链表的最后一个节点
cur = old_list.head
while cur.next:
cur = cur.next
cur.next = new_list.head
# 打印链表
cur = old_list.head
while cur:
print(cur.val, end=' ')
cur = cur.next
# 输出:4 5 1 2 3
```
阅读全文