链式结构的线性表--单链表

来源:互联网 发布:python labeled lda 编辑:程序博客网 时间:2024/06/04 19:43

顺序表和链表的区别

链表:

  1. 是可以实现动态分配的存储结构;
  2. 存储单元是地址零散的不是连续的;
  3. 频繁删除和插入操作,不能随机存取;
  4. 线性表的长度变化大时使用。

顺序表:

  1. 可以随机存取;
  2. 存储单元地址是连续的;
  3. 查找操作多,少插入和删除操作;
  4. 线性表长度变化不大时使用。

单链表的操作

#include<stdio.h>#include<stdlib.h>typedef int ElemType;typedef struct node{    ElemType data;    struct node* next;}SNode;ElemType creatlist(SNode* L,int n)      //建立线性表{    SNode * p,* r;    int i=1;    p=L;    for(i=1;i<=n;i++)    {        r=(SNode*)malloc(sizeof(SNode));        scanf("%d",& r->data);        p->next=r;        p=r;    }    p->next=NULL;    return 0;}ElemType print(SNode *L)                //打印线性表{    SNode *p;    p=L->next;    while(p)    {        printf("%d",p->data);        p=p->next;    }    printf("\n");    return 0;}ElemType length(SNode *L)                //计算线性表的长度{    SNode *p;    int i=0;    p=L->next;    while(p)    {        i++;        p=p->next;    }    printf("%d\n",i);    return(i);}ElemType get(SNode *L,int i)           //得到线性表第i个数据{    int j=1;    SNode *p;    p=L->next;    if(i<1)        return(-1);    while(j<i&&p)    {        p=p->next;        j++;    }    printf("%d\n",p->data);    return 0;}ElemType locate(SNode *L,ElemType x)   //得到x在线性表中的位置{    int i=1;    SNode *p;    p=L->next;    while(p&&p->data!=x)    {        p=p->next;        i++;    }    printf("%d\n",i);    if (p=NULL)        return (-1);    else         return (i);}int insnode(SNode * L,ElemType x,int i)//在第i个节点位置插入x{    SNode *p,*r;    int j=1;    p=L->next;    while(p&&j<i-1)    {        p=p->next;        j++;    }    if(p==NULL)        return(-1);    r=(SNode *)malloc(sizeof(SNode));    r->data=x;    r->next=p->next;    p->next=r;    return 0;}int delnode(SNode *L,int i)               //删除第i个节点数据{    SNode *p,*r;    int j=1;    p=L->next;    while(p&&j<i-1)    {        p=p->next;        j++;    }    r=p->next;    p->next=r->next;    printf("删除的是%d\n",r->data);    free(r);    return (r->data);}int main(){    SNode L;    creatlist(&L,5);    print(&L);    length(&L);    get(&L,3);    insnode(&L,6,3);    print(&L);    delnode(&L,3);    print(&L);    return 0;}

这里写图片描述

0 0
原创粉丝点击