一个程序了解链表的基本操作

基础请看:C++ 线性表知识点摘录
目的:输入 num 的值,表示(整数 data)链表的长度,进而设计链表的基本函数实现链表的输入,输出,排序,删除特定元素的操作,具体解释请看注释~
先看代码:

#include<iostream>
using namespace std;
struct node{
    
    
	int data;
	node*next;
};//创建链表,实质是结构与指针的结合使用
node*tailinsert(node*head,node*tmp);//尾部插入函数
node*headinsert(node*head,node*tmp);//头部插入函数
node*sortinsert(node*head,node*tmp);//按照从小到大的原则选择合适的位置插入
node*search(node*head,int n);//输出元素所在位置处往后的链表片段
node*delNode(node*head,int n,int &flag);//删除特定的节点
void output(node*head);//输出链表数据
void delList(node*head);//删除整个链表
node*tailinsert(node*head,node*tmp){
    
    
	tmp->next=NULL;
	if(head==NULL) return tmp;//单独考虑空链表
	node*p=head;
	while(p->next) p=p->next;
	p->next=tmp;//找到尾部就插入,别忘了 tmp 最后要指向 NULL 哦~
	return head;
}
node*headinsert(node*head,node*tmp){
    
    
	//if(head==NULL){
    
    
	//	tmp->next=NULL;return tmp;
	//}
	tmp->next=head;//一句话搞定~
	return tmp;
}
node*sortinsert(node*head,node*tmp){
    
    
	node*q=NULL;//p 与 q 始终保持前后关系,便于插入
	node*p=head;
	while(p && p->data<tmp->data){
    
    q=p;p=p->next;}
	if(q==NULL){
    
    //插入头部单独考虑
		tmp->next=p;return tmp;
	}
	tmp->next=p;//这一句与下一句顺序不能换,否则形成自我指向的死循环(想通为什么)
	q->next=tmp;
	return head;
}
node*search(node*head,int n){
    
    
	while(head){
    
    
		if(head->data==n) return head;//找到了就输出
	head=head->next;}
	return NULL;//没找到输出空
}
node*delNode(node*head,int n,int&flag){
    
    
	node*pre=NULL;
	node*cur=head;
	while(cur && cur->data!=n){
    
    
		pre=cur;
		cur=cur->next;
	}
	if(cur){
    
    
		if(pre){
    
    //表示删除位置不在链表头部
			pre->next=cur->next;//跳过了 cur,形成新的链表 head
			delete cur;
			flag=1;//记录成功删除一个(防止有多个)
			return head;
		}
		else{
    
    //删除位置在头部
			pre=cur->next;delete cur;
			flag=1;
			return pre;
		}
	}
	else{
    
    //没找到符合条件的就原样输出
		flag=0;
		return head;
	}
}
void output(node*head){
    
    
	while(head){
    
    cout<<head->data;
	head=head->next;
	if(head) cout<<"->";//data 之间用箭头连接
	}
	cout<<endl;
}
void delList(node*head){
    
    
	node*tmp=head;
	while(tmp){
    
    head=tmp->next;
	delete tmp;
	tmp=head;
	}
}
int main(){
    
    
	int n,i,num;
	node*head=NULL,*t;
	cin>>num;
	for(i=0;i<num;i++){
    
    
		cout<<"输入一个数:";
		cin>>n;
		t=new node;
		t->data=n;
		head=tailinsert(head,t);
	}
	output(head);
	node*nlist=NULL;
	while(head){
    
    
		t=head;head=head->next;nlist=sortinsert(nlist,t);
	}
	head=nlist;
	output(head);
	int flag=1;
	int delnum;
	cin>>delnum;
	while(flag) head=delNode(head,delnum,flag);
	output(head);
	delList(head);
	return 0;
}

测试示例:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/interestingddd/article/details/115357909