链表Set_LinkList(建立)

用单链保存集合元素,元素由键盘输入。输入以-1结束,将所建链表打印输出。

链表结构如下图所示:

提示:

1.链表中数据元素为整型,typedef int ElemType;

2.用结构体自定义链表结构Set_LinkList ;

3.初始化链表函数init(),该函数可创建空链表L,返回L的头指针地址;

4.链表插入结点函数insert(Set_LinkList L, ElemType e),该函数可以向链表中插入集合元素e,注意集合元素不可重复;

5.链表打印输出函数display(Set_LinkList L),该函数可以遍历打印输出链表L;

6.主函数中需调用链表初始化函数init()创建空链表,用循环获取用户输入,输入数据为整数,输入以-1结束,之后将链表打印输出。

输入格式:

一组整数,以空格分隔,以-1结束

输出格式:

链表中所保存的集合数据(按照输入顺序)

输入样例:

在这里给出一组输入。例如:

复制代码
9 4 0 7 1 5 6 9 8 7 9 6 5 4 1 2 3 6 5 -1

输出样例:

在这里给出相应的输出。例如:

复制代码
9 4 0 7 1 5 6 8 2 3

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
typedef int ElemType;
struct node{
    ElemType Data;
    struct node* next;
};
typedef struct node* Set_LinkList;
Set_LinkList init(){
    Set_LinkList L = (Set_LinkList)malloc(sizeof(struct node));
    L->Data = -1;
    L->next = NULL;
    return L;
}
void insert(Set_LinkList L, ElemType e){
    Set_LinkList p = L->next;
    if(p == NULL){
        Set_LinkList newnode = (Set_LinkList)malloc(sizeof(struct node));
        L->next = newnode;
        newnode->Data = e;
        newnode->next = NULL;
        return;
    }
    while(p->next != NULL){
        if(p->Data == e){
            return;
        }
        p = p->next;
    }
    Set_LinkList newnode = (Set_LinkList)malloc(sizeof(struct node));
    p->next = newnode;
    newnode->Data = e;
    newnode->next = NULL;
}
void display(Set_LinkList L){
    Set_LinkList p = L->next;
    if(p == NULL){
        return;
    }
    while(p->next != NULL){
        cout<<p->Data<<' ';
        p = p->next;
    }
}
int main()
{
    int x = 0;
    Set_LinkList L = init();
    while(x != -1){
        cin>>x;
        insert(L , x);
    }
    display(L);
    return 0;
}
相关推荐
LuminousCPP17 小时前
数据结构-双向循环链表
c语言·数据结构·笔记·链表
白狐_79818 小时前
408数据结构第5章:树与二叉树②——遍历、线索树、森林与哈夫曼
数据结构·算法·深度优先
Jasmine_llq20 小时前
《P15800 [GESP202603 六级] 选数》
数据结构·long long·逆序线性 dp·从后往前推导·转移严格遵循题意·防止总和溢出·复杂度on
疯狂打码的少年20 小时前
【数据结构】串(字符串):基本概念与存储
数据结构·笔记
纵有疾風起21 小时前
线性表的定义与基本操作 — 从逻辑结构到 ADT 接口
数据结构·算法·408·线性表·adt
wuyk5551 天前
1.栈:后进先出的线性数据结构
c语言·数据结构·stm32·单片机
LuminousCPP1 天前
数据结构-时间与复杂度|时间/空间复杂度 + 两道力扣练习 + 二分查找复盘
c语言·数据结构·经验分享·算法·leetcode
Nil2081 天前
leetcode 三数之和
数据结构·算法·leetcode
noipp1 天前
推荐题目:洛谷 P16689 出征
java·开发语言·数据结构·c++·算法·洛谷·luogu
青山木1 天前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode