单链表学习记录

从以下几个方面展开:

一、链表创建操作

二、链表长度计算

三、链表插入操作

四、链表删除操作

五、链表反转操作

1.节点的定义

struct stu
{
	int a;
	struct stu *next;
};

2.链表的创建

/*
	创建链表
	入口:n  表示链表长度 
*/
struct stu * create(int n)
{
	struct stu *head,*pf,*pb;
	int i=0;
	if(n==0)
	{
		head=NULL;	
	} 
	else
	{
		for(i=0;i<n;i++)
		{
			pb=(struct stu *)malloc(sizeof(struct stu));
			printf("Input a number
");
			scanf("%d",&pb->a);
			pb->next=NULL;
			if(i==0)
			{
				head=pf=pb;
			}
			else
			{
				pf->next=pb;
				pf=pb;
			}
			
		}
	}
	return head;
}

3.链表长度计算

/*
	计算链表长度 
*/ 
int getListLength(struct stu *head) 
{
  int cnt=0;
  struct stu *p=head;
    while(p!=NULL)
    {
    	cnt++;
    	p=p->next;
    }
    return (cnt);
}

4.找寻指定数据地址

/*
	寻找位置 
*/
struct stu * find(struct stu *head,int a)
{
	struct stu *p=head;
	while(p->next!=NULL&&p->next->a!=a)
	{
		p=p->next;
	}
	return p;
}

5.链表插入操作

/*
	链表插入数据 
*/
void insert(struct stu *postion,int a)
{
	struct stu *p=(struct stu *)malloc(sizeof(struct stu));
	struct stu *temp;
	p->a=a;
	temp=postion->next;
	postion->next=p;
	p->next=temp;		 
} 

6.链表删除操作

/*
	删除链表元素 
*/
void delete(struct stu *head,int a)
{
	struct stu *p=find(head,a);
	struct stu *temp=p->next->next;
	free(p->next);	
	p->next=temp;
}

7.链表反转操作

/*
	链表逆序操作 
*/
struct stu * reservList(struct stu *head)
{
	struct stu *p=head;
	struct stu *current,*p_next;
	current=p;
	p_next=p->next;
	while(p_next!=NULL)
	{
		p=p_next->next;
		p_next->next=current;
		current=p_next;
		p_next=p;	
	}
	head->next=NULL;
	return current;
}

8.链表的打印操作

/*
	打印链表数据 
*/
void printfList(struct stu *head)
{
	int i=0;
	struct stu *p=head;
	printf(">>>>>开始打印链表<<<<<
");
	while(p!=NULL)
	{
		i++;	
		printf("第%d个元素:%d
",i,p->a);
		p=p->next;
	}	
}

 

原文地址:https://www.cnblogs.com/achao123456/p/6278614.html