c++利用類進行單鏈表的插入,刪除,清空操作


#if 1

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <string>

using namespace std;

//類
class List
{
public:
	//構造器初始化,生成頭節點
	List()
	{
		head = new Node;
		head->next=NULL;
	}

	//成員函數
	void createList(); 
	void insertList(int data);
	void travelList();
	void input();
	int  addNode();
	void deleteData(int addNum);
	void ifClear();
	void clearList();
private:
	//數據成員
	struct Node
	{
		int data; //數據域
		struct Node * next;	//指針域
	
	} * head;//頭指針

	int num;//鏈表元素個數
};


//頭插法生成節點
void List::insertList(int data)
{
	Node * cur=new Node;

	//插入數據
	cur->data=data;

	//插入節點
	cur->next =head->next;
	head->next=cur;
}

//調用insertList輸入數據,生成鏈表
void List::input()
{
	cout<<"請輸入鏈表數量長度:";
	cin >>num;
	srand(time(NULL));
	for(int i=0;i<num;i++)
	{
		insertList(rand()%100);
	}
}

//任意位置插入節點
int List::addNode()
{
	int d,idx;

	cout<<"請輸入你要插入的節點數據:";
	cin >>d;
	cout<<"請輸入你要插入的節點位置: ";
	cin >>idx;

	Node *tp=NULL;
	Node *link=head;

	//尋找插入位置
	if(idx<1||idx>num+1)
		cout<<"操作非法"<<endl;
	else
	{
		for(int i=0;i<idx;i++)
		{
			tp=link;
			link=link->next;
		}

		Node *cur=new Node;
		tp->next=cur;
		cur->data=d;
		cur->next=link;
		travelList();
		return ++num;
	}
}

//遍歷鏈表並將數據存入文件
void List::travelList()
{
	ofstream mycout("D:/text.txt");
	Node *temp = head->next;	//防止頭指針地址改變
	while(temp != NULL)
	{
		cout<<temp->data<<"  ";
		mycout<<temp->data<<"  ";
		temp=temp->next;
	}
	mycout.close();
	cout<<endl;
}

//刪除節點
void List::deleteData(int addNum)
{
	int i,j=0;
	cout<<"請問您要刪除第幾個數據: ";
	cin >>i;
	Node *tp=NULL;
	Node *link=head;//link為刪除節點后面的一個節點,temp為刪除節點

	if(addNum<i||i<0)
		cout<<"操作非法!!"<<endl;
	else
	{
		while(link->next)
		{
			tp=link->next; //第一個節點
			j++;
			if(i==j)   //找的刪除的節點
			{
				link->next=tp->next;
				delete tp;
				break;
			}	
			link=link->next;
		}
		travelList();
	}

}

//清空鏈表
void List::clearList()
{
	Node *tp = NULL;
	Node *ph=head->next;

	while(head->next)
	{
		tp=ph;
		ph=ph->next;
		delete tp;
		head->next=ph;
	}

	travelList();
	cout<<endl;
}

//詢問是否清空
void List::ifClear()
{
	string i;

	if(!head->next)
	{
		cout<<"鏈表已清空!!!"<<endl;
	}
	
	else 
	{
		cout<<"是否清空鏈表(是/否):";
		cin>>i;
		
		if(i=="是")
		{
			clearList();
			cout<<"鏈表清空完成!!!"<<endl;
		}
		else
			cout<<"鏈表未清空!!!"<<endl;
	}
}

void main()
{
	//初始化,生成頭節點
	List list;

	//輸入鏈表長度
	list.input();

	//遍歷鏈表,並存入文件
	list.travelList();

	//添加節點並返回總結點數
	int addNum=list.addNode();

	//刪除節點
	list.deleteData(addNum);

	//是否清空鏈表
	list.ifClear();

	system("pause");

}
#endif

  

總結:漢字輸入需要用string,在頭文件string中;字符串比較可以直接用比較運算符;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM