1.什么是链表:
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
这里需要两个头文件
#include<stdio.h>
#include<stdlib.h>
2.链表的相关操作:
1.链表的创建:
struct node{
int date;
struct node *next;
};
int main()
{
int n,a,find,add,del;
scanf("%d",&n);
struct node *head,*p,*q,*t1,*t2,*t3,*t4;
head=NULL;
for(int i=0;i<n;++i){
scanf("%d",&a);
p=(struct node*)malloc(sizeof(struct node));
p->date=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
} ;
2.所需要的函数声明:
1.链表的查找:
t2=head;//查找
scanf("%d",&find);
while(t2!=NULL){
if(t2->date==find){
printf("%d",t2->date);
break;
}
t2=t2->next;
}
if(t2==NULL)
printf("NO");
2.链表的增添:
scanf("%d",&add);
while(t3!=NULL){
if(t3->next==NULL||t3->next->date>= add){
p=(struct node*)malloc(sizeof(struct node));
p->date=add;
p->next=t3->next;
t3->next=p;
break;
}
t3=t3->next;
}
//或者
for(t3=head;t3!=NULL;t3=t3->next){链表的增添
if(t3->next==NULL||t3->next->date>add){
p=(struct node*)malloc(sizeof(struct node));
p->date=add;
p->next=t3->next;
t3->next=p;
break;
}
}
3.链表删除:
scanf("%d",&del);//删除
for(t3=head;t3!=NULL;t3=t3->next){
if(t3->next->date==del){
t3->next=t3->next->next;
break;
}
}
4.链表输出
t1=head;
while(t1!=NULL){
printf("%d ",t1->date);
t1=t1->next;
}
4.链表逆置的方法:
1.头插法
遍历一次链表,在遍历的过程中将遍历到的节点头插至新的链表中
head= (struct node*)malloc(sizeof(stuct node));
head->next = NULL;
struct node *s;
int x;
while(scanf("%d",&x) && x!= -1) {
s = (struct node*)malloc(sizeof(struct node));
s->data = x;
s->next = head->next;
head->next = s;
}
return head;
}
2.就地逆置
struct node *p,*q;
p = head->next;
head->next = NULL;
while(p) {
q = p;
p = p->next;
q->next = head->next;
head->next = q;
}
}
完