对于链表的建立以及基本操作,可以分函数段实现但是由于对链表不是很熟悉,所以我就把链表的建立以及基本操作都给写到main函数里面吧;
首先来说明一下,一个完整指针有两个部分| data|next |data代表的是当前指针指向的数据,next表示的当前指针指向下一个数的data;
链表的建立很简单,就是先写一个头指针,让其指向空,然后输入一个数,申请一个指针的空间,让它指向输入的数,之后加一个判断如果头指针指向空就把刚那个指针值赋给头指针;如果不是让上一个指针的next指向当前指针;
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*t;
int i,n,a;
head=NULL;
scanf("%d", &n);
for(i=1; i<=n; i++)
{
scanf("%d", &a);
p=(struct node*)malloc(sizeof(struct node));
p->data =a;
p->next =NULL;
if(head==NULL)
head=p;
else
q->next =p;
q=p;
}
t=head;
while(t)
{
printf("%d ", t->data);
t=t->next;
}
printf("\n");
return 0;
}
链表的插入
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main()
{
struct node *p,*q,*t,*head;
int i,n,a;
int *e;
scanf("%d", &n);
head=NULL;
for(i=1; i<=n; i++)
{
scanf("%d", &a);
p=(struct node*)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
scanf("%d", &a);
t=head;
while(t)
{
if(t->next==NULL||t->next->data>a)
{
p=(struct node*)malloc(sizeof(struct node));
p->data=a;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
t=head;
while(t!=NULL)
{
printf("%d ", t->data);
t=t->next;
}
return 0;
}