算法笔记·链表(书中代码整理)

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值