链表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;
}
相关推荐
Fanxt_Ja21 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1231 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1121 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19431 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww1 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
_不会dp不改名_2 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构