单链表的基本操作

本文详细介绍了单链表的基本操作,包括如何创建链表,如何进行节点的插入,高效查找特定元素的方法,以及如何有效地删除指定节点。通过学习这些基本操作,可以深入理解单链表的数据结构和操作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、创建

#include<iostream>
using namespace std;

struct node
{
	int data;
	node* next;
};

node* create(int array[],int n)
{
	node* head=new node;
	head->next=NULL; //别忘记置空!! 
	node* pre=head;
	node* p;
	
	for(int i=0;i<n;i++)
	{
		p=new node;
		p->data=array[i];
		p->next=NULL;
		pre->next=p;
		pre=p;
	}
	return head; 
}

int main()
{
	int array[5]={1,2,3,4,5};
	node* l=create(array,5);
	l=l->next;
	while(l!=NULL)
	{
		cout<<l->data<<" ";
		l=l->next;
	}
	return 0;
}

2、插入

void insert(node* head,int pos,int x)
{
	node* p=head;
	for(int i=0;i<pos-1;i++)
	{
		p=p->next;
	}
	node* q=new node;
	q->data=x;
	q->next=p->next;
	p->next=q;	
}

3、查找

int search(node* head,int x)
{
	int count=0;
	node* p=head->next;
	while(p!=NULL)
	{
		if(p->data==x) count++;
		p=p->next; 
	}
	return count;
}

4、删除

void del(node* head,int x)
{
	node* pre=head;
	node* p=head->next;
	while(p!=NULL)
	{
		if(p->data==x) 
		{
			pre->next=p->next;
			delete(p);
			p=pre->next;  //注意p的指向的变动!! 
		}
		else  //非此即彼的关系 
		{
			pre=p;
			p=p->next;
		}		
	}	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值