大話數據結構 —— 單鏈表 C#、C++代碼實現

 


單鏈表


 線性表的鏈式存儲結構的特點:

  • 是用一組任意的存儲單元來存儲線性表的數據元素,這組存儲單元可以是連續的,也可以是不連續的 。

我們把存儲數據元素信息的域稱爲數據域,把存儲直接後繼位置的域稱爲指針域。 指針域中存儲的信息稱做指針或鏈。  這兩部分組成數據元素ai 的存儲映像,稱爲結點。

頭指針 :就是鏈表中的第一個結點的存儲位置叫做頭指針,那麼整個鏈表的存取就必須是從頭指針開始進行的。

爲了更方便地對鏈表進行操作,如刪除第一個結點的特殊情況(第一個結點沒有前驅,而要摘除一個結點需要首先找到它的前驅才能做摘除操作),經常在單鏈表的第一個結點前附設一個結點,稱爲頭節點,這樣頭指針就指向了頭結點。

頭指針和頭結點的異同:

  • 頭指針是指向列表第一個結點的指針,若鏈表有頭結點, 則是指向頭結點的指針。
  •  頭指針具有標識作用,所以常用頭指針冠以鏈表的名字
  •  無論鏈表是否爲空,頭指針均不爲空。 頭指針是鏈表的必要元素。
  • 頭結點是爲了操作的統一和方便而設立的,放在第一個元素的結點之前,其數據域一般無意義(也可存放鏈表的長度)。
  • 有了頭結點,對第一個元素結點前插入結點和刪除第一結點,其操作與其它結點的操作就統一了。

指針變量和結點變量:

 指針變量p和結點變量*p的關係:

 

  指針變量P 結點變量*P
定義 在變量說明部分顯示定義 在指針變量P使用時,通過標準的new生成
取值 結點的地址 結點各個域的內容
操作方式 指針變量名訪問 通過 *取值運算符訪問

結點域的訪問

  • (*p).data 和 (*p).next
  • p->data 和 p->next

指針變量p和結點變量*p的關係 :

  • 指針變量 p的值是結點的地址
  • 結點變量 *p的值是結點的內容
  • *((*p).next)是*p後繼結點的內容


優點:相對於數組,刪除和插入效率高 
缺點:相對於數組,查詢元素和獲取元素效率低 


要執行插入操作,只需要如下的代碼:

s->next = p->next
p-next = s ; 


執行刪除操作,只需要如下的代碼:

p->next = p->next->next 

或者

q = p->next;
p->next = q->next;

 單鏈表結構和順序表存儲結構的優缺點:

結論:

  • 若線性表需要頻繁查找,很少進行插入和刪除操作,採用順序表,若需要頻繁插入和刪除時,採用單鏈表。
  • 當線性表中的元素個數變化較大或者根本不知道有多大時,最好用單鏈表結構,這樣可以不需要考慮存儲空間的大小問題。 而如果事先知道線性表的大致長度,順序表效率更好

下面用 C++ 語言 實現單鏈表:

單鏈表的頭文件:

#include<iostream>
#include<cassert>
using namespace std;
#ifndef TT_CHAIN_LIST
#define TT_CHAIN_LIST
#define TT_OK 1
#define TT_ERROR 0

namespace tt
{
	class ChainList
	{
	public:
		using ElemType = int;
		using Status = void;
	public:
		struct Node
		{
			ElemType m_data;  //數據域
			Node *m_next;  //指針域
		};
	public:
		ChainList();
		~ChainList();
		ElemType insertAt(ElemType i, ElemType elem);
		ElemType removeAt(ElemType i, ElemType &elemOut);
		ElemType getAt(ElemType i, ElemType &elemOut);
		ElemType destroy();

		ElemType getIndexElemAt(ElemType &i, ElemType elemOut);//查找與e相等的元素,返回第一個與e相等元素在線性表中的下標,否則,返回0
		ElemType isEmpty()const;
		Status getLength()const;
		ElemType clear();
		Status show();
		Status createTail(ElemType *datas, ElemType length);//創建長度爲length的鏈表,數據通過數組指定,這裏採用尾插法
	    Status createHead(ElemType *datum, ElemType extent);

		ElemType priorElemAt(ElemType cur_e, ElemType &pri_e);//若cur_e是鏈表的數據元素,且不是第一個,則用pre_e返回它的前驅
		ElemType nextElemAt(ElemType cur_e, ElemType &Nex_e); //若cur_e是鏈表的數據元素,且不是最後一個,則用next_e返回它的後繼,
		Status reverseList();  //反轉列表
		Node *recurReverseList(Node *heap); // 遞歸反轉列表
	private:
		Node *m_heap;  //頭結點
	};

	inline ChainList::ElemType ChainList::isEmpty()const
	{
		return (m_heap->m_data == 0);
	}
	inline ChainList::Status ChainList::getLength()const
	{
		cout << "當前的單鏈表中的數據爲:" << (m_heap->m_data) << "\n" << endl;
	}
}
#endif //TT_CHAIN_LIST

單鏈表的源文件:

#include"ChainList.h"

namespace tt
{
	ChainList::ChainList()
	{
		m_heap = new Node;
		assert(m_heap != nullptr);
		m_heap->m_next = nullptr;
		m_heap->m_data = 0;
		cout << "********************單鏈表初始化成功********************" << "\n" << endl;
	}
	ChainList::~ChainList()
	{
		this->destroy();
	}
	ChainList::Node *ChainList::recurReverseList(Node *heap) // 遞歸反轉列表
	{
		if (!(m_heap->m_next) || m_heap->m_data == 1)
		{
			cout << "鏈表中沒有數據,或者只有一個元素,無法進行反轉!" << endl;
			system("pause");
			exit(0);
		}
		Node *newHead = recurReverseList(heap->m_next); //一直循環到鏈尾 
		heap->m_next->m_next = heap;                       //翻轉鏈表的指向
		heap->m_next = nullptr;                          //記得賦值NULL,防止鏈表錯亂
		return nullptr;
	}
	ChainList::Status ChainList::reverseList()
	{
		if (!(m_heap->m_next) || m_heap->m_data == 1)
		{
			cout << "鏈表中沒有數據,或者只有一個元素,無法進行反轉!" << endl;
			system("pause");
			exit(0);
		}
		Node *p = m_heap->m_next; //用指針p指向第一個節點
		m_heap->m_next = nullptr;  // 頭結點和第一個結點斷開
		Node *q = nullptr, *pr = nullptr;
		while (p)
		{
			pr = p->m_next; //第一次循環,指針pr指向p的後繼結點,就是第二個元素
			p->m_next = q; //第一次循環,p的後繼結點 是q
			q = p;  //第一次循環,把q指向第一個節點
			p = pr; //第一次循環,把p指向第二個節點
		}
		m_heap->m_next = q; //p指針指向nullptr時,讓原頭節點的指針域指向原來最後一個元素節點(現在是第一個節點q)。此時鏈表倒置已完成。
	}
	ChainList::Status ChainList::createTail(ElemType *datas, ElemType length)  //單鏈表的整表創建,尾插法
	{
		m_heap->m_data = length;
		Node *m = m_heap;    //聲明一個節點指針指向頭結點
		for (int i = 0; i < length; ++i)
		{
			Node *n = new Node;  //每次循環都給新元素分配空間
			n->m_data = datas[i];   //每次循環都把要存儲的新元素依次存儲到數據域中
			m->m_next = n;  //第一次循環的時候,把新節點n變成頭結點的後繼節點,就是第一個元素,
			m = n;   //將當前的新結點定義爲表尾終端結點
		}
		m->m_next = nullptr;
	}
	ChainList::Status ChainList::createHead(ElemType *datum, ElemType extent)  //寫的頭插法
	{
		m_heap->m_data = extent;
		Node *s = new Node;
		if (!m_heap->m_next)
		{
			s->m_data = datum[0];
			s->m_next = nullptr;
			m_heap->m_next = s;

		}
		for (int i = 1; i < extent; ++i)
		{
			Node *m = new Node;
			m->m_data = datum[i];
			m->m_next = s;
			m_heap->m_next = m;
			s = m;
		}	
	}

	ChainList::ElemType ChainList::priorElemAt(ElemType cur_e, ElemType &pri_e)
	{
		/*Node *p = m_heap->m_next;
		while (p)
		{
		Node *q = p->m_next;
		if (q && (q->m_data == cur_e))
		{
		pri_e = p->m_data;
		return TT_OK;
		}
		p = q;
		}
		return TT_ERROR;*/

		Node *p = m_heap->m_next,*q;
		while (p->m_next) //p所指結點有後繼
		{
			q = p->m_next;
			if (q->m_data == cur_e)
			{
				pri_e = p->m_data;
				return TT_OK;
			}
			p = q;
		}
		return TT_ERROR;
	}

	ChainList::ElemType ChainList::nextElemAt(ElemType cur_e, ElemType &Nex_e)
	{
		/*Node *p = m_heap->m_next;
		while (p->m_next)   //p所指結點有後繼
		{
		if (p->m_data == cur_e)
		{
		Nex_e = p->m_next->m_data;
		return TT_OK;
		}
		p = p->m_next;
		}
		return TT_ERROR;*/

		Node *p = m_heap->m_next,*q;
		while (p)
		{
			 q = p->m_next;  //q爲p的後繼

			if (q && (p->m_data == cur_e)) //p有後繼,且p的數據域與當前值相等
			{
				Nex_e = q->m_data;
				return TT_OK;
			}
			p = q;
		}
		return TT_ERROR;
	}
	ChainList::ElemType ChainList::insertAt(ElemType i, ElemType elem) //插入元素,  在線性表中第i個位置之前插入新元素elem
	{
		Node *q = m_heap;  //首先把q指針指向頭結點
		int j = 1;
		while (q && j < i)  //當q還沒有爲空時, 當前的位置已經超過了要查找的位置,直接退出循環
		{
			q = q->m_next;
			++j;

		}
		if (!q || j > i)  //q還沒有指向空,噹噹前的位置已經超過了要找的位置,但還是沒有找到,就返回錯誤
		{
			return TT_ERROR;
		}

		Node *s = new Node;
		s->m_data = elem;
		s->m_next = q->m_next;     //將q的後繼節點變成s的後繼節點
		q->m_next = s;            //將s變成q的後繼節點
		++m_heap->m_data;
		return TT_OK;
	}
	ChainList::ElemType ChainList::removeAt(ElemType i, ElemType &elemOut)
	{

		Node *s = m_heap;
		int j = 1;
		while ((s->m_next) && (j < i))
		{                    //寫 s->m_next 是怕沒有結點,寫s的話,當沒有結點的時候,刪除會錯誤
			s = s->m_next;  //s的指針向後移動不斷指向下一個節點
			++j;
		}
		if (!(s->m_next) || (j > i))
		{
			return TT_ERROR;
		}
		Node *q = s->m_next;   //將s的後繼節點變成q
		s->m_next = q->m_next;    //再把q的後繼節點變成s的後繼節點
		elemOut = q->m_data;  //將q節點的數據給element
		delete q;   //讓系統回收此節點,釋放內存
		--m_heap->m_data;
		return TT_OK;
	}
	ChainList::ElemType ChainList::getAt(ElemType i, ElemType &elemOut)
	{
		Node *q = m_heap->m_next;    //讓q指向鏈表的第一個節點
		int j = 1;  //從一個節點開始循環遍歷,就是當前位置
		while (q && (j < i))
		{                       /*當q還沒有爲空時, 當前的位置已經超過了要查找的位置,直接退出循環*/

			q = q->m_next;
			++j;
		}
		if ((!q) || (j > i))   //q還沒有指向空,噹噹前的位置已經超過了要找的位置,但還是沒有找到,就返回錯誤
		{
			return TT_ERROR;
		}
		elemOut = q->m_data;   //取第i個元素的數據
		return TT_OK;
	}
	ChainList::ElemType ChainList::getIndexElemAt(ElemType &i, ElemType elemOut)//在線性表中查找與elem的相等的元素,返回第一個與elem相等元素在線性表中的第幾個位置
	{
		Node *p = m_heap->m_next;    //從第一個結點開始遍歷
		int searchLocation = 1;
		while (p && (p->m_data != elemOut))  //只要p不爲空, 還沒有找到元素,循環繼續
		{
			++searchLocation;
			p = p->m_next;
		}
		if (!p)
		{
			return TT_ERROR;
		}
		i = searchLocation;
		return TT_OK;
	}
	ChainList::ElemType ChainList::clear()
	{
		Node *m = m_heap->m_next,*n;  //把頭節點的後繼節點變成m
		while (m != nullptr)   //當還有節點存在時,就循環繼續
		{
			n = m->m_next;  //然後把m的後繼節點變成n
			delete m;   //刪除第一個節點,每循環一次都刪除第一個節點
			m = n;  //然後把n變成m, n就變成了第一個節點
		}
		m_heap->m_next = nullptr;   //頭結點指向的第一個結點清空
		m_heap->m_data = 0;
		return TT_OK;
	}
	ChainList::Status ChainList::show()
	{
		if (!m_heap->m_data)
		{
			cout << "此單鏈表中沒有數據,無法顯示!" << "\n" << endl;
		}
		else
		{
			Node *p = m_heap->m_next;
			cout << "輸出單鏈表的所有元素:";
			while (p)
			{
				cout << p->m_data << ",";
				p = p->m_next;

			}
			cout << endl;
		}
	}
	ChainList::ElemType ChainList::destroy()  //單鏈表銷燬
	{
		Node *s = nullptr;
		while (m_heap)
		{
			s = m_heap->m_next;
			delete m_heap;
			m_heap = s;
		}
		m_heap = nullptr;
		return TT_OK;
	}
}

//測試myChainList
void testChainList()
{
	tt::ChainList myChainList;    //創建一個單鏈表對象

	//struct Node *pHead = nullptr;
	int myLength(0);    //單鏈表的整表創建,尾插法
	cout << "想創建多少數據的鏈表?";
	cin >> myLength;
	int *myDatas = new int[myLength];
	cout << "請依次輸入這" << myLength << "個數據,中間以回車符隔開:" << endl;

	for (int i = 0; i < myLength; ++i)
	{

		cin >> myDatas[i];  //輸入要存儲的數據的值
	}
	myChainList.createTail(myDatas, myLength);   //調用create函數 建立單鏈表
	myChainList.getLength();
	myChainList.show();

	while (true)
	{
		{
			cout << "\n\n*************************************************************" << endl
				<< "*******************   單鏈表的基本功能展示   *******************" << endl
				<< "*****************************************************************" << endl
				<< "********************   選擇1——數據插入.   **********************" << endl
				<< "********************   選擇2——數據刪除.   **********************" << endl
				<< "********************   選擇3——獲取元素.   **********************" << endl
				<< "********************   選擇4——查找元素.   **********************" << endl
				<< "********************   選擇5——是否爲空.   **********************" << endl
				<< "********************   選擇6——獲取線性表的長度.   **********************" << endl
				<< "********************   選擇7——清空元素.   **********************" << endl
				<< "********************   選擇8——輸出所有元素. ************************" << endl
				<< "********************   選擇9——銷燬單鏈表. ************************" << endl
				<< "*********************  選擇10——獲得元素的前驅.  *****************" << endl
				<< "*********************  選擇11——獲得元素的後繼.  *****************" << endl
				<< "********************   選擇12——清屏!      ************************" << endl
				<< "********************   選擇13——單鏈表反轉.      ************************" << endl
				<< "********************   選擇0——退出程序!   ************************" << endl
				<< "***********************************************************************" << endl
				<< "***********************************************************************" << endl;
		}
		cout << "\n********************   請輸入你想要使用的單鏈表功能的序號   ***************" << endl;
		cout << "請輸入你的選擇:";
		int userChoice(0);
		cin >> userChoice;
		if (userChoice == 0)
		{
			cout << "程序已退出,感謝您的使用!" << "\n" << endl;
			break;
		}
		switch (userChoice)
		{
		case 1:
		{
			int pushDatas(0);  //要插入的元素
			int indexLocition(0);  //要插入的位置
			cout << "請輸入你想要插入的元素位置:";
			cin >> indexLocition;
			cout << "請輸入你想要插入的元素:";
			cin >> pushDatas;
			if (myChainList.insertAt(indexLocition, pushDatas))
			{
				cout << "數據" << pushDatas << "插入成功!" << "\n" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			else
				cout << "數據" << pushDatas << "插入失敗!可能是插入的位置不合理!~" << endl;
			break;
		}
		case 2:
		{
			int popLocation(0);
			int popElement(0);
			cout << "請輸入要刪除數據第幾個位置:";
			cin >> popLocation;
			if (myChainList.removeAt(popLocation, popElement))
			{
				cout << "數據" << popElement << "刪除成功!" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			else
				cout << "數據" << popElement << "刪除失敗!可能是刪除的位置不合理,或者鏈表中沒有元素!" << endl;
			break;
		}
		case 3:
		{
			int getElem(0);        //要獲取的元素
			int indexLocition(0);
			cout << "請輸入你想要獲取元素的位置:";
			cin >> indexLocition;
			if (myChainList.getAt(indexLocition, getElem))
			{
				cout << "獲取的元素爲:" << getElem << "\n" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			else
			{
				cout << "當前單鏈表爲空或者尚未建立,數據獲取失敗!"<< endl;
				myChainList.getLength();
			}
			break;
		}
		case 4:
		{
			int findElement(0);   //查找元素
			int findLocation(0);
			cout << "請輸入要查找的元素:";
			cin >> findElement;
			if (myChainList.getIndexElemAt(findLocation, findElement))
			{
				cout << "找到了元素" << findElement << ",其在表中的索引值爲:" << findLocation << "\n" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			else
			{
				cout << "鏈表中不存在所需找的值!" << "\n" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			break;
		}
		case 5:
			if (myChainList.isEmpty())   //判斷是否爲空
			{
				cout << "目前該線性表爲空!" << endl;
				myChainList.getLength();
			}
			else
			{
				cout << "目前線性表非空!" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			break;
		case 6:
		{
			myChainList.getLength();
			myChainList.show();
			break;
		}
		case 7:
			if (myChainList.clear())  //清空單鏈表
			{
				cout << "目前單鏈表已經被清空!" << endl;
				myChainList.getLength();
			}
			else
			{
				cout << "目前單鏈表非空!" << endl;
				myChainList.getLength();
				myChainList.show();
			}
			break;
		case 8:
			myChainList.show();  //顯示所有元素
			myChainList.getLength();
			break;
		case 9:
		{                                                //銷燬單鏈表
			cout << "你確定要銷燬該單鏈表嗎?(若銷燬請輸入輸入(Y/y))";
			char yesOrNo;
			cin >> yesOrNo;
			if ((yesOrNo == 'Y') || (yesOrNo == 'y'))
			{
				if (myChainList.destroy())
				{
					cout << "單鏈表已被銷燬." << "\n" << endl;
				}
				else
					cout << "單鏈表銷燬失敗." << "\n" << endl;
			}
			break;
		}
		case 10:
		{
			int priorElem(0);
			int getElem(0);
			cout << "輸入你想要獲得哪一個元素的前驅?(注意:不能獲取第一個元素的):";
			cin >> priorElem;
			if (myChainList.priorElemAt(priorElem, getElem))
			{
				cout << "數據元素" << priorElem << "的,前驅元素是:" << getElem << endl;
				myChainList.show();
			}
			else
			{
				cout << "獲取前驅元素失敗,不能獲取第一個元素的前驅或者鏈表中沒有你輸入的元素!" << endl;
				myChainList.show();
			}
			break;
		}
		case 11:
		{
			int backElem(0);
			int getElem(0);
			cout << "輸入你想要獲得哪一個元素的後繼?(注意:不能獲取最後一個元素的):";
			cin >> backElem;
			if (myChainList.nextElemAt(backElem, getElem))
			{
				cout << "數據元素" << backElem << "的,後繼元素是:" << getElem << endl;
				myChainList.show();
			}
			else
			{
				cout << "獲取後繼元素失敗!不能獲取最後一個元素的後繼或者鏈表中沒有你輸入的元素!" << endl;
				myChainList.show();
			}
			break;
		}
		case 13:
		{
			myChainList.reverseList();
			myChainList.show();
			break;
		}
		case 12:
			system("cls");
			cout << "屏幕已經清屏,可以重新輸入!" << "\n" << endl;
			break;
		default:
			cout << "輸入的序號不正確,請重新輸入!" << "\n" << endl;
		}

	}
	delete[] myDatas;
	myDatas = nullptr;
}
int main()
{
	testChainList();
	system("pause");
	return 0;
}

下面用 C# 代碼實現 單鏈表:

namespace DateStructure
{
    interface IListDS
    {
        int GetLength();
        void Clear();
        bool IsEmpty();
        void AddToTail(int item);
        void InsertAt(int item, int pos);
        int RemoveAt(int pos);
       int GetEle(int pos);
        int LocateElem(int value);
        void Show();
        void createTail(params int[] arrElem);
    }
    class Node
    {
        private int m_data;
        private Node m_next;

        public Node()
        {
            m_data = 0;
            m_next = null;
        }
        public int m_Data
        {
            get { return m_data; }
            set { m_data = value; }
        }
         public Node m_Next
        {
            get { return m_next; }
            set { m_next = value; }
        }             
    }
    class MySqList : IListDS
    {
        private Node m_head;
        public MySqList() // 創建頭結點
        {
            m_head = new Node();
            if(m_head == null)
            {
                WriteLine("單鏈表初始化失敗!");
                return;
            }          
        }
        public void createTail(params int[] arrElem) // 單鏈表的尾插法
        {
            m_head.m_Data = arrElem.Length;
            Node temp = m_head;
            for(int i =0; i!= arrElem.Length;++i)
            {
                Node newNode = new Node();
                newNode.m_Data = arrElem[i];
                temp.m_Next = newNode;
                temp = newNode;
            }
            temp.m_Next = null;
        }
        public void AddToTail(int item)
        {
            Node newNode = new Node();
            if(m_head == null) // 如果剛好單鏈表只有一個頭結點,那麼插入的新節點是第一個結點元素
            {
                m_head.m_Next = newNode;
                m_head.m_Data = item;
                ++m_head.m_Data;
            }
            else
            {
                Node temp = m_head;
                for (int i = 0; i != m_head.m_Data; ++i)
                {
                    temp = temp.m_Next;
                }
                temp.m_Next = newNode;
                newNode.m_Data = item;
                //newNode.m_Next = null;
                ++m_head.m_Data;
            }
        }

        public void Clear()
        {
            m_head.m_Data = 0;
            m_head.m_Next = null;
        }
      
        public int GetEle(int pos) // 獲取某個位置的元素是什麼
        {
            if (pos < 1 || m_head.m_Data == 0 || pos > m_head.m_Data)
            {
                WriteLine("獲取元素的位置不正確,或者該單鏈表爲空!");
                return -1;
            }
            Node temp = m_head;
            int locitionPos = 1;
            while(locitionPos < pos)
            {
                temp = temp.m_Next;
                ++locitionPos;
            }
            return temp.m_Next.m_Data;         
        }

        public int GetLength()
        {
            return m_head.m_Data;
        }

        public void InsertAt(int item, int pos)
        {
            if ((pos < 1) || (pos > ((m_head.m_Data) + 1)))   //i位置不合理時,返回false
            {
                WriteLine("插入元素失敗,插入的位置不正確!");
                return;
            } 
            if(m_head.m_Next == null)
            {
                AddToTail(item);
            }
            Node temp = m_head;
            int locitionPos = 1;
            while (locitionPos < pos)
            {
                temp = temp.m_Next;
                ++locitionPos;
            }
            Node newNode = new Node();
            newNode.m_Data = item;
            newNode.m_Next = temp.m_Next;
            temp.m_Next = newNode;
            ++m_head.m_Data;
        }

        public bool IsEmpty()
        {
            return m_head.m_Data == 0;
        }

        public int LocateElem(int value) // 查找某個元素在什麼位置
        {
            if(m_head.m_Data == 0)
            {
                WriteLine("該單鏈表爲空,無法進行查找!");
                return -1;
            }
            Node temp = m_head;
            for(int i=0;i!=m_head.m_Data;++i)
            {
                temp = temp.m_Next;
                if(temp.m_Data == value)
                {
                    return i + 1;                 
                }
            }
            return -1;
        }

        public int RemoveAt(int pos)
        {
            if( pos < 1 || m_head.m_Data == 0 || pos > m_head.m_Data)
            {
                WriteLine("刪除的位置不正確,或者該單鏈表是個空表,沒有元素可以刪除!");
                return -1;
            }
            Node temp = m_head;
            int locitionPos = 1;
            while(locitionPos < pos)
            {
                temp = temp.m_Next;
                ++locitionPos;
            }
            int removaElem = m_head.m_Next.m_Data;
            temp.m_Next = temp.m_Next.m_Next;
            --m_head.m_Data;
            return removaElem;
        }

        public void Show()
        {
           if(m_head.m_Data == 0)
            {
                WriteLine("該單鏈表中沒有數據,無法顯示!");
                return;
            }
           else
            {
                Node temp = m_head;
                Write("輸出此時單鏈表中所有的元素:");
                for(int i= 0; i!=m_head.m_Data;++i)
                {
                    temp = temp.m_Next;
                    Write($"{temp.m_Data},");
                }
                WriteLine();
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
          
            MySqList myList = new MySqList();

            const int arraySize = 5;
            int[] myIntArray = new int[arraySize] { 0, 22, 33, 44,55 };
            myList.createTail(myIntArray);
            myList.AddToTail(555);
            myList.Show();

            WriteLine("請輸入你想要查找的元素的值:");          
            int locationPosElem = Convert.ToInt32(Console.ReadLine());
            int temp = myList.LocateElem(locationPosElem);
            if(0 <= temp )
            {
                WriteLine($"該元素的位置序號是:{temp}");
                myList.Show();
            }
            else
            {
                WriteLine("該元素不再鏈表中!");
            }
            
            WriteLine("請輸入你想獲取單鏈表中哪一個位置的元素:");
            int getArrElem = Convert.ToInt32(Console.ReadLine());
            WriteLine($"該位置的元素是:{myList.GetEle(getArrElem)}");
            myList.Show();


            WriteLine("請輸入你想插入的元素值:");
            int pushElem = Convert.ToInt32(Console.ReadLine());
            WriteLine("請輸入你想插入的位置:");
            int pushLocition = Convert.ToInt32(Console.ReadLine());
            myList.InsertAt(pushElem, pushLocition);
            WriteLine($"\n獲取當前單鏈表的總個數:{myList.GetLength()}");
            myList.Show();


            WriteLine("請輸入你想刪除哪一個位置的元素:");
            int removePosElem = Convert.ToInt32(Console.ReadLine());
            myList.RemoveAt(removePosElem);
            WriteLine($"\n獲取當前單鏈表的總個數:{myList.GetLength()}");
            myList.Show();
          
           if (myList.IsEmpty())
             {
                 WriteLine("當前的單鏈表爲空!");
             }
             else
                 WriteLine("當前的單鏈表非空!");
             WriteLine($"\n獲取當前單鏈表的總個數:{myList.GetLength()}");
             myList.Clear();
             WriteLine($"獲取當前單鏈表的總個數:{myList.GetLength()}");
        }
    }
}

 

 

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