自学内容网 自学内容网

链表Set_LinkList(建立)

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

链表结构如下图所示:

image.png

提示:

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

#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;
}

 


原文地址:https://blog.csdn.net/alwaysandnever/article/details/142796854

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!