c语言链表基本常识

//1.顺序建立链表
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0;i<n;i++){
    p=(struct node*)malloc(sizeof(struct node));
    p->next=NULL;
    tail->next=p;
    tail=p;
}
//2.逆序建立链表
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
for(i=0;i<n;i++){
    p=(struct node*)malloc(sizeof(struct node);
    p->next=head->next;
    head->next=p;
}
//3.链表的合并
p=head1->next;
q=head2->next;
head1->next=NULL;
tail=head1;
while(p&&q){
    if(p->data<q->data){
        tail->next=p;
        tail=p;
        p=p->next;
        tail->next=NULL;
    }
    else {
        tail->next=q;
        tail=q;
        q=q->next;
        tail->next=NULL;
    }
}
if(p)tail->next=p;
else  tail->next=q;
//4.链表的拆分
head1=(struct node*)malloc(sizeof(struct node));
head1->next=NULL;
tail1=head1;
head2=(struct node*)malloc(sizeof(struct node));
head2->next=NULL;
tail2=head2;
a=head->next;
while(a){
   if(a->data%2){
      p=(struct node*)malloc(sizeof(struct node));
      p->next=NULL;
      p->data=a->data;
      tail1->next=p;
      tail1=p;
   }
   else{
    q=(struct node*)malloc(sizeof(struct node));
    q->next=NULL;
    q->data=a->data;
    tail2->next=q;
    tail2=q;
   }
   a=a->next;
}
//5.链表的删除
d=head->next;
while(d){
    p=d;
    q=p->next;
    while(q){
         if(d->data=q->data){
             p->next=q->next;
             q=q->next;
         }
         else {
            p=q;
            q=q->next;
         }
    }
    d=d->next;
}
//6.指定位置插入节点
p=head;
while(m--&&p->next){
    p=p->next;
}
q=(struct node*)malloc(sizeof(struct node));
q->next=NULL;
q->data=x;
q->next=p->next;
p->next=q;
//7.双向链表
struct node{
    int data;
    struct node*next;
    struct node*prior;
}
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0;i<n;i++){
    p=(struct node*)malloc(sizeof(struct node));
    p->next=NULL;
    tail->next=p;
    p->prior=tail;
    tail=p;
}
**//8.约瑟夫问题**
    tail->next=head;  
    p=head;
    q=tail;
    int k=0;
    while(p!=p->next)
    {
        k++;
        if(k==m)
        {
            **q->next=p->next;
            p=p->next;**//删除元素操作
            k=0;
           
        }
        else
        {
            **q=p;
            p=p->next;**
        }
    }

区别插入与删除
删除:p->next=q->next;
q=q->next;
插入:q->next=p->next;
p->next=q;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值