单链表的增添删改(C语言)

来源:互联网 发布:linux教程xwindows 编辑:程序博客网 时间:2024/06/06 02:04


创建一个结构体



#include <stdio.h>
typedef struct student
{
    int data;
    struct student *next;
}Node;

//创建单链表头插法
Node *Creatlist(int a[],int n)
{
    Node *first=(Node *)malloc(sizeof(Node));//为首节点开辟内存
    first->next=NULL;  //将首节点的指针域初始化
    Node *s=NULL;
    for(int i=0;i<n;i++)
    {
        s=(Node *)malloc(sizeof(Node)); //为下一个节点开辟内存
        s->data=a[i];  //对数据域赋值
        s->next=first->next;//对指针域赋值
        first->next=s; 
    }
    return first;
}
//创建单链表头插法
Node *Creatlisty(int a[],int n)
{
    Node *s=NULL,r=NULL;
    Node *first=(Node *)malloc(sizeof(Node)); // 生成头节点
    r=first;// 尾指针初始化
    for(int i=0;i<n;i++)
    {
        s=(Node *)malloc(sizeof)(Node);
        s->data=a[i]; //为数据域赋值
        r->next=s;//为尾指针赋值
        r=s;
    }
    r->next=NULL;//单链表建立完毕,将终端节点的指针域置空
    return first;
}
//打印单链表
void Printlist(Node *first)
{
    Node *p=first->next;
    while(p!=NULL)
    {
        printf("%d",p->data);
        p=p->next;
    }
}
//求链表的长度
int length(Node *first)
{
    Node *p=first->next;
    int count=0;
    while(p!=NULL)
    {
        count++;
        p=p->next;
    }
    return count;
}
// 按值查找
int Locatelist(Node *first,int x)
{
    Node *p=first->next;
    int count=1;
    while(p!=NULL)
    {
        if(p->data==x);
        return count;
        count++;
    } 
}

//按位查找
int Getlist(Node *first,int x,int *ptr)
{
    Node *p=first->next;
    int count=1;
    while(p!=NULL&&count<i)
    {
        p=p->next;
        count++;
    }
    if(p==NULL)
    {
        printf("查找失败");
        return 0;
    }
    else
    {
        return *ptr->data;
    }
}

//插入操作
void Insert(Node *first,int n,int x)
{
    Node *p=first;
    Node *s=NULL;
    int count=0;
    while(p!=NULL&&count<n-1)
    {
        count++;
        p=p->next;
    }
    if(p==NULL)
    {
        printf("插入失败");
    }
    else
    {
        s=(Node *)malloc(sizeof)(Node);
        s->data=x;
        s->next=p->next;
        p->next=s;
    }
}
//删除操作
void Delete(Node *first,int n,int *ptr)
{
    Node *p=first;
    int count=0;
    Node *s=NULL;
    while(p!=NULL&&count<n-1)
    {
        count++;
        p=p->next;
    }
    if(p==NULL||p->next==NULL)
    {
        printf("删除失败");
    }
    else
    {
        *ptr=p->data;
        s=p->next;
        p->next=s->next;
        free(q);
    }
}// 销毁操作
void Destory(Node *first)
{
    Node *p=first;
    while(p!=NULL)
    {
        first=first->next;
        free(p);
        p=first;
    }
}

 
原创粉丝点击