数据结构链表小结

.需要先清楚一点,指针指向的是地址!!!

1.创建链表,插入数据
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
struct student
{
    int data;
    struct student *next;
 };
 
 int main()
 {
     int a[10]={1,2,3,4,5,6,7,8,9,10};/*无头节点-头插法*/ 
     struct student *head=NULL,*p;
     for(int i=0;i<10;i++)
     {
         p=(struct student*)malloc(sizeof(struct student));
         p->next=NULL;
         p-> data=a[i];
         p->next=head;/*指针指向的是地址*/ 
         head=p;
      } 
      p=head;/*head不能带着一直跑会乱掉*/
      while(p!=NULL)
      {
          printf("%d ",p->data);
          p=p->next;
       } return 0;
 }
#include<stdio.h>
#include<stdlib.h>
struct stu
{
    int data;
    struct stu *next;
};
int main()
{
    int a[3]={1,2,3};
    struct stu *List,*p;/*带头节点*/ 
    List=(struct stu*)malloc(sizeof(struct stu));
    List->next=NULL; 
    for(int i=0;i<3;i++)
    {
        p=(struct stu*)malloc(sizeof(struct stu));
        p->data=a[i];
        p->next=List->next;
        List->next=p;
    }
    p=List->next;/*从第一个节点开始*/ 
    while(p)
    {
        printf("%d",p->data);
        p=p->next;
    }return 0;
    
}

2.尾插法
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
struct stu
{
    int data;
    struct stu *next;
};
int main()
{
    int a[5]={1,2,3,4,5};
    struct stu *head=NULL,*tail=NULL,*p;
    for(int i=0;i<5;i++)
    {
        p=(struct stu*)malloc(sizeof(struct stu));
        p->data=a[i];p->next=NULL; 
        
        
        if(head)
        {tail->next=p;
        
            
        }else
        {
                head=p;}
        tail=p;
        
    }p=head;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next; 
         
    }return 0;
}
#include<stdio.h>
#include<stdlib.h>
struct stu
{
    int data;
    struct stu *next;
};
int main()
{
    int a[3]={1,2,3};
    struct stu *List,*tail=NULL,*p;
    List=(struct stu*)malloc(sizeof(struct stu));
    List->next=NULL;
    tail=List;
    for(int i=0;i<3;i++)
    {
        p=(struct stu*)malloc(sizeof(struct stu));
        p->data=a[i];
        p->next=NULL;
        tail->next=p;
        tail=p;
        
     } p=List->next;
     while(p)
     {
         printf("%d ",p->data);
         p=p->next;
     }return 0;
    }

遍历链表

for(p=head;p!=NULL;p=p->next) 
    {
        printf("%d",p->data); 
    }
while(p)
     {
         printf("%d ",p->data);
         p=p->next;
     }

3.删除节点
在这里插入图片描述
在这里插入图片描述

if(q->data==2)
        {
            p->next=q->next;
            free(q);
            q=p->next;
        }else
        {
            p=p->next;
            q=p->next;
        }

创造不易,三连关注一下吧~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值