数据结构实验二 单链表简单操作

概率论课上闲来无事,顺手把数据结构实验写了,
要求如下
一、实验目的
熟悉某种数据结构在计算机上实现的方法。掌握单链表的定义、创建、插入、删除、遍历等基本操作的实现。体会单链表操作、有序表插入、删除的一般方法。
二、实验内容问题描述:
已知递增有序的单链表A,编写算法实现向A中插入或删除一个元素,并保持A的有序性。
实验要求:结点的数据均为整型。若表中已经存在此元素,则不插入

代码如下
样例输入;
1 3 5 7 9 0
2 4 6 7 8 0
6
样例输出;
9 7 5 3 1
9 8 7 6 5 4 3 2 1
9 8 7 5 4 3 2 1

#include<iostream>//按序插入 
#define ERROR -1
#define exist 1
#define OK 0
using namespace std;
//Author Spark
typedef struct LNode
{
    int data;
    struct LNode *next;
}
LNode,*linklist;
void init(linklist &L)
{
    L = (linklist)malloc(sizeof(LNode));
    L->next = NULL;
}
void Create_linklist(linklist &L)
{
    linklist p;
    int data;
    while(cin>>data&&data != 0)
    {
        p = (linklist)malloc(sizeof(LNode));
        p->data = data;
        p->next = L->next;
        L->next = p;
    }
}
int lenlist(linklist L)
{
    int cnt = 0;
    while(L->next)
    {
        cnt++;
        L=L->next;
    }
    return  cnt;
}
int searchList(linklist L,int n)
{
    int cnt = 0;
    while(L->next)
    {
        cnt ++;
        if(L->next->data == n){
            return cnt;
            break;
        }
        L=L->next;
    }
    return 0;
}
int insertElem(linklist &L,int n)
{
    if(searchList(L,n))
        return exist;
    linklist tmp = L;
    do tmp = tmp->next;
    while(tmp&&tmp->next->data > n);
    linklist s = new LNode;
    s->data = n;
    s->next = tmp->next;
    tmp->next = s;
    return OK;
}
void TranverseList(linklist L)
{
    while(L->next)
    {
        cout<<L->next->data<<" ";
        L=L->next;
    }
    cout<<endl;
}
int delElem(linklist &L,int n)
{
    int cnt = searchList(L,n)-1;
    if(cnt==-1)return ERROR;
    linklist ptr=L->next;
    linklist pre=L;
    while(cnt--&&ptr)
    {
        pre=pre->next;
        ptr=ptr->next;
    }
    if(ptr==NULL&&cnt>0)return ERROR;
    pre->next=ptr->next;
    free(ptr);
    return OK;
}
int main()
{
    linklist L;
    init(L);
    Create_linklist(L);
    TranverseList(L);
    int n;
    while(cin>>n&&n!=0)
        insertElem(L,n);
    TranverseList(L);
    int tmp;
    cin>>tmp;
    delElem(L,tmp);
    TranverseList(L);
    return 0;
}

心得体会
手机打代码真难受

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值