单链表的基础操作

单链表的基础操作 包括: 查找、插入、删除、创建链表等。

 

以下直接用程序进行说明:

 

#include<stdlib.h> //  malloc  free 头文件
#include <stdio.h>


 

// 节点定义
typedef struct Node
{  
	int data;
	struct Node *next;
}Node;


 

// 查找第一个值为X的节点
Node *Serach(Node *pHead,int x)
{	
	Node *p=pHead;
	while(p!=NULL && p->data!=x)
		p=p->next;
	return p;
}


 

// 在p节点之后进行插入
void Insert(Node *p,int x)   
{	
	Node *s;
	s=(Node*)malloc(sizeof(Node));
	s->data=x;
	s->next=p->next;
	p->next=s;
}


 

// 删除 p->next节点
void DeleteFollowNode(Node *p)       
{	
	Node *q;

	q=p->next; 

	if(q!=NULL)
	{
		p->next=q->next;
		free(q);
	}
}

// 删除 p节点
void Delete(Node *p,Node *pHead)       
{	

	if (p==NULL)
		return;

	Node *qPre=pHead;
	while(qPre!=NULL&&qPre->next!=p)
		qPre=qPre->next;


	if (qPre!=NULL&&p!=NULL)
	{
		qPre->next=p->next;
		free(p);
	}
}


 

// 创建链表, 新节点在插入到最前面
Node* CreateListAhead(int a[],int n) 
{
	Node *s,*pHead;
	int i;
	pHead=(Node*)malloc(sizeof(Node));
	pHead->data=0;
	pHead->next=NULL; 

	// 新节点 在最前面进行插入
	for(i=n-1;i>=0;i--)
	{
		s=(Node*)malloc(sizeof(Node));
		s->data=a[i];
		s->next=pHead->next;
		pHead->next=s;
	}
	return pHead;
}

// 创建链表, 新节点在插入到末尾
Node* CreateListTail(int a[],int n) 
{
	Node *s,*pHead,*pTail;
	int i;
	pHead=(Node*)malloc(sizeof(Node));
	pHead->data=0;
	pHead->next=NULL; 

	pTail=pHead;

	// 新节点 插入到末尾
	for(i=0;i<n;i++)
	{
		s=(Node*)malloc(sizeof(Node));
		s->data=a[i];
		s->next=NULL;

		pTail->next=s;
		pTail=s;
	}
	return pHead;
}


 

//遍历链表
void Print(Node *h)
{  

	Node *p;
	p=h->next;
	while(p!=NULL)
	{ 
		printf("%d,",p->data);
		p=p->next;
	}
	printf("\n");
}


 

//应用实例
void main()
{ 
	int a[]={3,2,1,4,5};

	Node *pHead,*p;
	pHead=CreateListTail(a,5);
	Print(pHead);

	p=Serach(pHead,4);
	printf("%d\n",p->data);

	p=pHead->next->next;
	Insert(p,9);
	Print(pHead);

	p=pHead->next->next->next;
	Delete(p,pHead);
	Print(pHead);

	while(getchar()!='a')
		;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清水迎朝阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值