#include<stdio.h>
struct node{
int data;
node *next;
};
node* create(node *head,int Arry[]){
node *p,*ptr;
ptr=head;
for(int i=0;i<10;i++){//创建链表
p=new node;
p->data=Arry[i];//新结点p的数据域是数组的值
p->next=NULL;//新结点p的指针域设为NULL
ptr->next=p;
ptr=ptr->next;//等价于ptr=p;
}
return head;//返回头结点
}
int search(node*head,int x){//以head为头结点的链表上记录元素x的个数
node*p=head->next;//从第一个结点处开始
int count=0;
while(p!=NULL){
if(p->data==x){
count++;
}
p=p->next;
}
return count;
}
void insert(node* head,int pos,int x){
node*ptr=head;
for(int i=0;i<pos-1;i++){
ptr=ptr->next;//pos-1是为了插入位置的前一个结点(结点的顺序不是从0到n,而是从1到n)
}
node*q=new node;
q->data=x;
q->next=ptr->next;
ptr->next=q;
}
void Print(node *head){
node*ptr=head->next;
while(ptr!=NULL){
printf("%d",ptr->data);
ptr=ptr->next;
}
}
void del(node *head,int x){
node *ptr=head->next;
node *pre=head;//作为ptr的前驱结点
while(ptr!=NULL){
if(ptr->data==x){
pre->next=ptr->next;
delete(ptr);
ptr=pre->next;
}
else{//++"循环增"
pre=ptr;
ptr=ptr->next;
}
}
}
int main(){
int Arry[10]={5,3,6,1,2,5,3,6,6,1};
node *head;
head=new node;
head->next=NULL;
node* L=create(head,Arry);//新建一个链表L
L=L->next;//从第一个结点开始有数据域
while(L!=NULL){
printf("%d",L->data);
L=L->next;
}
printf("\n");
int x=search(head,6);
printf("%d",x);
printf("\n");
insert(head,3,9);
Print(head);
printf("\n");
del(head,6);//把链表里的6都删除了
Print(head);
printf("\n");
return 0;
}
算法笔记·链表(书中代码整理)
最新推荐文章于 2023-03-30 19:27:10 发布