线性表(部分)

1.线性表的长度是线性表中元素个数

2.c语言的“结构”类型:

struct node
{
  ElemType data;//data为抽象元素类型
  struct node *next;//next为指针类型
};
指向结点的指针类型head,p,q说明
struct node *head,*p,*q;

用typedef定义指针类型

typedef struct node
{
  ElemType data;
  struct node *next;
}node,*Linklist;
指针变量head,p,q的说明
Linklist head,p,q;

3.结点类型的定义

#define LENG sizeof(struct node)
struct nade
{
    int data;//数据为int型
    struct node* next;
};

4.生成单链表

每次输入新元素后:

1.生成新结点:p=malloc(结点大小)

 p->data=e;p->next=null;

2.将结点添加到表尾:tail->next=p;

3.设置新表尾:tail=p;

应用:

a.生成“先进行先出”单链表

struct node*creat1()
{
  struct node*head,*tail,*p;
  int e;
  head=(struct node*)malloc(LENG);
  tail=head;
  scanf("%d",&e);
 while(e!=0)
 {
  p=(struct node*)malloc(LENG);
  p->data=e;
  tail->next=p;
  tail=p;
  scanf("%d",&e);
  }
tail->next=null;
return head;
}

b.生成“后进先出”的单链表

struct node*creat2()
{
   struct node*head,*p;
   int e;
   head=(struct node*)malloc(LENG);//生成头结点;
   head->next=NULL;//制成空表
   scanf("%d",&e);
   while(e!=0)
  {
    p=(struct node*)malloc(LENG);
    p->data=e;
    p->next=head->next;
    head->next=p;
    scanf("%d",&e);
  }
   return head;
}

5.链表的插入,删除

a.在指定位置插入元素:

int insert(LinkList &L,int i,ElemType e)
{
    p=L;
    j=1;
   while(p&&j<i)
   {
      p=p->next;
      j++;
   }
if(i<1||p==NULL)  return ERROR;//插入点错误;
f=(LinkList)malloc(LENG);
f->data=e;
f->next=p->next;
p->next=f;
return OK;
}

b.在带表头结点的单链表删除元素值为e的结点:

int Deletel(LinkList head,ElemType e)
{
   struct node*p,*q;
   q=head,p=q->next;
   while(p&&p->data!=e)
{
   q=p;
   p=p->next;
}
if(p)//有元素为e的结点
{
q->next=p->next;
free(p);
return YES;
}
else
 return NO;
}

c.删除指定位置上的结点:

int Deletel(LinkList &L,int i,ElemType &e)
{
   struct node*q;
   p=L;
   j=1;
  while(p->next&&j<i)
{
   p=p->next;
   j++;
}
if(i<1||p->next=NULL)
return ERROR;
q=p->next;
p->next=q->next;
e=q->data;
free(q);
return OK;
}

6.循环链表:

a.求以head为头指针的循环链表的长度:

int length(struct node*head)
{
   int length=0;
   struct node*p;
   p=head->next;
   while(p!=head)
{
    printf("%d",p->data);
    p=p->next;
    length++;
}
return length;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值