鏈表及其各種函數操作的實現方法

代碼中主要實現了下面四個操作:

下面幾種操作都是線性操作,算法複雜度都是O(n);

  1. 鏈表插入默認是按關鍵字大小插入鏈表的,所以最後得到的結果是從大到小排好序的,分三種情況(1)鏈表爲空(2)插入的點最小,插在鏈表最前面;(3)插入鏈表中間;(4)插入鏈表結尾。
  2. 鏈表刪除是在鏈表中找到要刪除的關鍵字,然後刪除該節點,如果有兩個以上,只刪一個。如果沒有就返回。刪除操作必須釋放刪除結點所申請的內存:
  3. 查找最大理論上就是最後一個,查找最小理論上就是第一個結點。但是我爲了通用性寫成了遍歷整個鏈表查找最大和最小的結點。(如果找最小直接返回第一個節點算法複雜度爲O(1))
  4. 打印鏈表,從頭到尾打印鏈表。

主函數中我一函數運行時間爲種子生成了一個隨機數組,然後一個一個插入鏈表。


#include<iostream>
#include<time.h>
using namespace std;
#define N 100
struct list{
	int val;
	list* next;
};
list *temp=NULL,*head=NULL;
int insertlist(int data){
	temp=new list;//臨時結點保存要插入的值,
	              //每次重新申請空間,因爲在外面定義,全局變量
	              //所以不用擔心申請的空間在函數結束時被系統銷燬
	temp->val=data;
	if(head==NULL){//如果鏈表中沒有值的時候
		temp->next=NULL;
		head=temp;
		return 0;
	}
	list* node=new list;//記錄用來與插入值對比的下一個節點,
	                    //必須新申請空間,因爲指向地址不停在變,
	                    //不申請的話頭指針所指向地址也跟着變
	                    //局部變量,函數返回時自動銷燬所申請內存
	list* nodelast;//記錄node上一個節點,可以不用申請新內存
	node=head;
	while(node){
		if(data<head->val){//如果插入第一個
			temp->next=head;//把當前頭節點的地址賦給臨時變量的下一個
			head=temp;//把頭指針換爲新結點
			return 0;
		}
		else if(data<node->val){//如果在中間插入
			temp->next=node;
			nodelast->next=temp;//node上一個節點指向新插入的節點
			return 0;
		}
		else{
			nodelast=node;
			node=node->next;
		}
	}
	temp->next=NULL;//在最後插入
	nodelast->next=temp;
	return 0;
}
int deletelist(int data)
{
	if(head==NULL)
	{
		cout<<"鏈表爲空"<<endl;
		return 0;
	}
	if(head->val==data)
	{
		list *t=NULL;
		t=head;
		head=head->next;
		delete t;
		return 0;
	}
	temp=new list;
	temp=head;
	while(temp->next)
	{
		if(temp->next->val==data)
		{
			list *t=NULL;
			t=temp->next;
			temp->next=temp->next->next;
			delete t;
			return 0;
		}
		temp=temp->next;
	}
	cout<<"鏈表中沒有"<<data<<endl;
	return 0;
}
int findmax()
{
	int max=0;
	if(head==NULL)
	{
		cout<<"鏈表爲空"<<endl;
		return 0;
	}
	temp=new list;
	temp=head;
	while(temp)
	{
		if(temp->val>max){
			max=temp->val;
		}
		temp=temp->next;
	}
	return max;
}
int findmin()
{
	int min=65565;
	if(head==NULL)
	{
		cout<<"鏈表爲空"<<endl;
		return 0;
	}
	temp=new list;
	temp=head;
	while(temp)
	{
		if(temp->val<min){
			min=temp->val;
		}
		temp=temp->next;
	}
	return min;
}
int printlist()
{
	list* node=new list;//子
	node=head;
	while(node){
		cout<<node->val;
		if(node->next)
			cout<<"->";
		node=node->next;
	}
	cout<<endl;
	return 0;
}
int main()
{
	int number[N],j,t;
	for(int i=0;i<N;i++)
		number[i]=i;
	srand((unsigned)time(NULL));
	for(int i=0;i<N;i++)//隨機生成1到N的數組
	{
		j=rand()%N;
		t=number[i];
		number[i]=number[j];
		number[j]=t;
	}
	cout<<"插入前:";
	for(int i=0;i<N;i++)
	{
		cout<<number[i];
		if(i<N)
			cout<<"->";
	}
	cout<<endl<<endl<<"插入後:";
	for(int i=0;i<N;i++)
	{
		insertlist(number[i]);
	}
	deletelist(99);
	deletelist(0);
	printlist();
	cout<<endl<<endl<<"鏈表中最大值爲:"<<findmax()<<endl;
	cout<<endl<<endl<<"鏈表中最小值爲:"<<findmin()<<endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章