编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。
时间: 2024-03-23 14:18:27 浏览: 52
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = Node()
def insert(self, data):
new_node = Node(data)
current = self.head
while current.next and current.next.data < data:
current = current.next
new_node.next = current.next
current.next = new_node
def display(self):
current = self.head.next
while current:
print(current.data, end=' ')
current = current.next
print()
def destroy(self):
current = self.head
while current:
temp = current.next
del current
current = temp
def main():
list1 = LinkedList()
list2 = LinkedList()
while True:
try:
data = int(input())
except:
break
if data > 0:
list1.insert(data)
else:
list2.insert(data)
list1.display()
list2.display()
list1.destroy()
list2.destroy()
if __name__ == '__main__':
main()
```
输入样例:
```
1
2
-1
-2
3
-3
0
```
输出样例:
```
1 2 3
-3 -2 -1
```
阅读全文