7-3 有序链表的插入 (20分)

已知一个递增有序链表L(带头结点,元素为整数),编写程序将一个新整数插入到L中,并保持L的有序性。 其中单链表的类型定义参考如下:

typedef int elementType;

typedef struct lnode

{ elementType data;

struct lnode *next;

}Lnode,* LinkList;

输入格式:

输入分三行

第一行 元素个数

第二行 元素的值,元素间用空格分隔。

第三行 待插入的元素值

输出格式:

在一行中输出有序链表元素值,每个元素前输出一个空格以便与相邻元素分隔。

输入样例:

5
1 3 5 7 9
4
输出样例:

1 3 4 5 7 9

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
    int num,x;
    cin>>num;
    num++;
    vector<int> v;
    while(num--){
       cin>>x;
        v.push_back(x);
    }
    sort(v.begin(),v.end());
    for(auto it = v.begin();it!=v.end();it++)
        cout<<" "<<*it;
    return 0;
}
}
有序链表插入数据需要保证插入后依然保持有序。具体步骤如下: 1. 创建一个新节点,将要插入数据存储在该节点。 2. 如果链表为空,则将新节点设置为头节点。 3. 如果链表不为空,则从头节点开始遍历链表,直到找到第一个大于等于插入数据的节点。记住该节点的前一个节点。 4. 将新节点插入到该节点的前面,即将前一个节点的 next 指针指向新节点,将新节点的 next 指针指向当前节点。 5. 如果遍历到链表末尾仍未找到大于等于插入数据的节点,则将新节点插入链表末尾。 以下是一个示例代码: ```python class Node: def __init__(self, data=None): self.data = data self.next = None class SortedLinkedList: def __init__(self): self.head = None def insert(self, data): new_node = Node(data) if self.head is None: # 如果链表为空,则将新节点设置为头节点 self.head = new_node elif self.head.data >= data: # 如果新节点的值比头节点小或相等,则将新节点插入到头节点前面 new_node.next = self.head self.head = new_node else: # 从头节点开始遍历链表,直到找到第一个大于等于插入数据的节点 current = self.head while current.next is not None and current.next.data < data: current = current.next # 将新节点插入到该节点的前面 new_node.next = current.next current.next = new_node def display(self): current = self.head while current is not None: print(current.data, end=' ') current = current.next print() ``` 可以使用以下代码测试: ```python linked_list = SortedLinkedList() linked_list.insert(3) linked_list.insert(2) linked_list.insert(5) linked_list.insert(4) linked_list.display() # 输出:2 3 4 5 ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值