数据结构之链表

本文介绍了链表作为数据结构的特点,与数组相比,链表的存储空间不连续,每个节点包含值域和指向下一个节点的指针。内容涵盖链表的创建、单向遍历、反向输出、删除节点以及插入节点的操作。
摘要由CSDN通过智能技术生成

数组,存储空间大,且连续,而链表与之相反,它的存储区域是不连续的空间单元;

链表中除了头节点没有前驱,尾节点没有后继之外,其余都会有前驱和后继此文中暂不提及环链

链表的每个节点都是一个结构体单元,至少有两个域,一个为值域,一个为存储下一个节点地址的指针域

其结构体可声明为:

typedef struct node{
 int data;
 struct node *next;
}ElemSN;

创建一条链:

ElemSN *createlink(int n)
{
    ElemSN *h;
    int x;
    if(n){
        h=(ElemSN *)malloc(sizeof(ElemSN));
        scanf("%d",&x);
        h->data=x;
        h->next=createlink(--n);
    }
    return h;
}

ElemSN *createlink2(int n)
{
    ElemSN *h,*p,*t;
    int x;
    int i;
    for(i=0;i<n;i++){
      p=(ElemSN *)malloc(sizeof(ElemSN));
      scanf("%d",&x);
      p->next=NULL;
      p->data=x;
      if(!i)  h=t=p;
      else t=t->next=p;
    }
    return h;
}

单向遍历链表:

void  PrintLink(ElemSN *h){
    ElemSN *p;
    for(p=h;p;p=p->next){
      printf("%d",p->data);
    }
}

反向输出链表:

void  NPrintLink(ElemSN *h){
    ElemSN *p,*end;
    end=NULL;
    while(end-h){
      for(p=h;p->next-end;p=p->next);
      printf("%d",p->data);
      end=p;
    }
}

删除节点(假设有重复的点–我遇到一面试题):

ElemSN * Delete(ElemSN *h,int key){
ElemSN *p,*q,*t,*head;
head=h;
for(p=h;p;p=p->next){
     if(p->data==key){  //若为头节点
        q=t=p;
       if(p==h) head->next=h->next; 
       else{ 
        q->next=p->next;
        }
        free(t);
   }
}
if(!p)  printf("Not found\n");
return head;
}

插入一个节点(分为头插,尾插,中间插):

//假设该原链表是有序的
ElemSN * Insert(ElemSN *h,int key){
ElemSN *p,*q,*t,*head;
head=h;
for(p=h;p&&p->data>key;q=p,p=p->next);
t=(ElemSN *)malloc(sizeof(ElemSN));
t->data=key;
t->next=NULL;
if(p==h){ //头插
   t->next=h;
   head=t;
}else if(p==NULL){//尾插
   p->next=t;
}else{//中间插入
   t->next=p;
   q->next=t;
}
return head;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值