链表的整表创建以及删除

链表的整表创建以及删除


单链表整表创建的算法思路:

  1. 声明一个结点P;
  2. 初始化一个空的链表L;
  3. 让L的头结点的指针指向NULL,即建立一个带头结点的单链表;
  4. 循环:
    △ 生成一新结点赋值给p;
    △ 随机生成一数字赋值给p的数据域p->data;
    △ 讲p插入到头结点与前一新结点之间
//创建一个单链表
void creat(LinkList *L,int n)
{
    
    
	LinkList p;  //声明头结点
	srand(time(0));    //随机生成数
	(*L)=(LinkList)malloc(sizeof(note));
	(*L)->next=NULL;
	for(int i=1;i<=n;i++){
    
    
		p=(LinkList)malloc(sizeof(note));  //生成一个新节点
		p->data=rand()%1000+1;   //生成一个1000以内的数字赋值给p
		p->next=(*L)->next;  
		(*L)->next=p;         //让头结点指向p
	}
} 

单链表整表删除的算法思路

  1. 声明一结点p和q;
  2. 将第一个结点赋值给p;
  3. 循环
    △ 将下一个结点赋值给q;
    △ 清空p;
    △ 将q赋值给p;
void clear(LinkList *L)
{
    
    
	LinkList p,q;   //声明结点p和q
	p=(*L)->next;   //p为第一个结点
	while(p){
    
    
		q=p->next;    //q为第二个结点
		free(p);     //清空第一个结点
		p=q->next;   //把q结点赋值给p
	}
	(*L)->next=NULL;  //头结点指针域设置为空
}

完整代码如下

#include<bits/stdc++.h>
using namespace std;
typedef struct note{
    
    
	int data;
	struct note *next;
}note;
typedef struct note *LinkList;
int n;

void creat(LinkList *L,int n)
{
    
    
	LinkList p;
	srand(time(0));
	(*L)=(LinkList)malloc(sizeof(note));
	(*L)->next=NULL;
	for(int i=1;i<=n;i++){
    
    
		p=(LinkList)malloc(sizeof(note));
		p->data=rand()%1000+1;
		p->next=(*L)->next;
		(*L)->next=p; 
	}
} 

void clear(LinkList *L)
{
    
    
	LinkList p,q;
	p=(*L)->next;
	while(p){
    
    
		q=p->next;
		free(p);
		p=q->next;
	}
	(*L)->next=NULL;
}
int main()
{
    
    
	LinkList k,LA;
	cin>>n;
	creat(&LA,n);
	k=LA->next;	
	while(k){
    
    
		cout<<k->data<<" ";
		k=k->next;
	}
	cout<<endl; 
	clear(&LA);
	k=LA->next;
	if(k==NULL) cout<<"以清空"<<endl;
	else{
    
    
		while(k){
    
    
			cout<<k->data<<" ";
			k=k->next;
		}
	} 
	return 0;
} 

解题完毕!

猜你喜欢

转载自blog.csdn.net/qq_45735298/article/details/108784919