1.单链表(增删改查看)
1.创建节点
typedef struct lnode
{
elemtype data;
struct lnode *next;//结构体指针
}node,*nn;//可以起多个别名,nn就相当于指向自己相同类型的结构体的指针
首先要创建一个节点,结构体类型的数据
主要分为数据域和指针域。
2.创建链表
node* headlist(int a[],int n)
{
node *head,*s;
head= (node*)malloc(sizeof(node));
head->next=NULL;
for(int i=0;i<n;i++)
{
s=(node*)malloc(sizeof(node));
s->data=a[i];
s->next=head->next;
head->next=s;
}
return head;//用指向头节点的指针来表示整个链表
}
这里的输入为一个数组,n为要输入的数据的个数。
返回值就是头结点的指针,这里需要分清楚头指针、头结点,首元节点的区别。(头结点无数据域)
3.查找
按值查找
node* findvaluelist(node* l,int i)//按照值来寻找节点,如果没有就返回null
{
node*p=l->next;//p为头指针,l为头结点,l.next是头结点指针域,存放首元节点
while (p!=NULL&&p->data!=i)
{
p=p->next;
}
return p;
}
按照位置查找
node* findposition(node* l,int i)//根据链表中节点位置查找对应元素值
{
node *p=l->next;
for(int j=0;j<i;j++)
{
p=p->next;
}
return p;
}
4.删除
node* findeposition(node* l,int i)//删除第n个节点
{
node* p=l;
int j=0;
while((p->next)&&(j<i-1))//区别于插入,这里只有n个元素可以删除,8/9,查找到了最后一个元素
{
p=p->next;
j++;
}
if(!(p->next)||(j>i-1))
return p=NULL;
node* q=p->next;
p->next=q->next;
free(q);
}
5.打印数据
void showlist(node* l)
{
node* p=l;
while(p)
{
printf("%d",p->data);
p=p->next;
}
printf("数据已经输出完毕");
}
链表作为数据的一种,最直观的方法还是打印
6.下面附上完整的代码
#include <stdio.h>
#include<stdlib.h>
//结构体
typedef struct lnode
{
elemtype data;
struct lnode *next;//结构体指针
}node,*nn;//可以起多个别名,nn就相当于指向自己相同类型的结构体的指针
node* headlist(int a[],int n)
{
node *head,*s;
head= (node*)malloc(sizeof(node));
head->next=NULL;
for(int i=0;i<n;i++)
{
s=(node*)malloc(sizeof(node));
s->data=a[i];
s->next=head->next;
head->next=s;
}
return head;//用指向头节点的指针来表示整个链表
}
node* findvaluelist(node* l,int i)//按照值来寻找节点,如果没有就返回null
{
node*p=l->next;//p为头指针,l为头结点,l.next是头结点指针域,存放首元节点
while (p!=NULL&&p->data!=i)
{
p=p->next;
}
return p;
}
node* findposition(node* l,int i)//根据链表中节点位置查找对应元素值
{
node *p=l->next;
for(int j=0;j<i;j++)
{
p=p->next;
}
return p;
}
node* findeposition(node* l,int i)//删除第n个节点
{
node* p=l;
int j=0;
while((p->next)&&(j<i-1))//区别于插入,这里只有n个元素可以删除,8/9,查找到了最后一个元素
{
p=p->next;
j++;
}
if(!(p->next)||(j>i-1))
return p=NULL;
node* q=p->next;
p->next=q->next;
free(q);
}
void showlist(node* l)
{
node* p=l;
while(p)
{
printf("%d",p->data);
p=p->next;
}
printf("数据已经输出完毕");
}
///下面为主函数
int main(void)
{
//创建一个链表
int a[10]={};//c创建空数组
for(int i=0;i<10;i++)
{
a[i]=i;
printf("%d\n",a[i]);
}
node *p=headlist(a,8);//只有八个数的链表
showlist(p);
node*c=findvaluelist(p,4);
printf("%d\n%d\n",c->data,p->data);//没有赋值的结构体变量值为0
node*m=findposition(p,6);
printf("%d\n",m->data);
findeposition(p,5);
showlist(p);
printf("Press Enter to exit...\n");//让终端停下
getchar(); // Wait for user input
return 0;
}