创建一个结构体
#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;}}