线性表基本操作

 ///线性表学习总结
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
typedef int ElemType;
typedef struct node
{
    node *next;
    ElemType data;
    int length;
}node;
///初始化
void InitList(node *L)
{
    L->data=0;
    L->length=0;
    L->next=NULL;
}
///新增节点 - 尾插法
void AddList(node *L,int n)
{
    L->length+=n;
    srand(time(0));
    for(int i=0;i<n;i++)
    {
        while(L->next!=NULL)
        {
            L=L->next;
        }
        node *c=(node*)malloc(sizeof(node));
        L->next=c;
        c->next=NULL;
        c->data=rand()%100+1;
    }
}
///头插法
void AddListHead(node *L,int n)
{
    L->length+=n;
    for(int i=0;i<n;i++)
    {
        node *c=(node*)malloc(sizeof(node));
        c->next=L;
    }
}
///插入节点
void InsertList(node *L,int i,int x)
{
    if(i>L->length || i<0)
    {
        cout<<"ERROR!\n";
        exit(0);
    }
    L->length++;
    int j=0;
    while(L->next!=NULL && j<i)
    {
        L=L->next;
        j++;
    }
    node *c=(node*)malloc(sizeof(node));
    c->next=L->next;
    L->next=c;
    c->data=x;
}
///删除节点
void DeleteList(node *L,int i)
{
    if(i<0 || i>L->length)
    {
        cout<<"ERROR!\n";
        exit(0);
    }
    L->length--;
    int j=0;
    while(L->next!=NULL && j<i-1)
    {
        L=L->next;
        j++;
    }
    node *c=L->next;
    L->next=c->next;
    free(c);
}
///获得某一位置节点
node* GetList(node *L,int i)
{
    if(i<0 || i>L->length)
    {
        cout<<"ERROR!\n";
        exit(0);
    }
    int j=0;
    while(L->next!=NULL&&j<i)
    {
        L=L->next;
        j++;
    }
    return L;
}
///输出链表
void PrintList(node *L)
{
    cout<<"the length of List is : "<<L->length<<endl;
    while(L->next!=NULL)
    {
        cout<<L->data<<"->";
        L=L->next;
    }
    cout<<L->data<<endl;
}
///清空节点
void ClearList(node *L)
{
    node *p,*q;
    p=L->next;
    while(p)
    {
        q=p->next;
        free(p);
        p=q;
    }
    L->next=NULL;
    L->length=0;
}
int main()
{
    node *head=(node*)malloc(sizeof(node));
    cout<<"Initalize:\n";
    InitList(head);
    PrintList(head);
    cout<<"Add 10 :\n";
    AddList(head,10);
    PrintList(head);
    cout<<"Insert number 3 ,1111:\n";
    InsertList(head,3,1111);
    PrintList(head);
    node *c=GetList(head,4);
    cout<<"Get numeber "<<4<<":\n";
    cout<<c->data<<" "<<c->next<<endl;
    cout<<"Delete number 4:\n";
    DeleteList(head,4);
    PrintList(head);
    ClearList(head);
    cout<<"Clear List :\n";
    PrintList(head);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值