數據結構——1 單鏈表建立、輸出和測長

單鏈表——建立、輸出和測長


創建單鏈表,並輸出鏈表,查找鏈表中某個結點元素,測試鏈表的長度(結點個數)。

鏈表操作中一種習慣是將頭結點作爲第一個結點,另一種是頭結點起標記作用,它後面的結點作爲第一個結點,個人喜好這種方式,個人。

#include<iostream>
using namespace std;
struct node       //node結構體,裏面有一個node指針,用來指向下一個node對象
{
	int x;
	node *next;   //指向什麼類型的對象,就用什麼類型的指針
};


node* create(int n)         //創建鏈表,參數n表示結點的個數,返回類型是結點指針node*
{
	node *head=new node;    //建立頭結點
	node *p=head;           //創建用於往後指的node指針


	for(int i=0;i<n;i++)
	{
		node *temp=new node;     //new一個node指針
		temp->x=rand()%100;
		p->next=temp;            //將p的next指向創建的temp,把新節點連接到鏈表後面
		p=temp;                  //將p指向新結點temp,即p移動到下一個節點
	}
	p->next=NULL;                //創建完成後,p->next指向NULL


	return head;
}

int getLength(node *head)        //求鏈表的長度,參數head表示鏈表的頭結點,返回值是鏈表的長度,即結點個數
{
	node *p;
	p=head->next;                //p重新指向頭結點後的那個結點,即for循環創建的第一個結點
	int len=0;


	while(p!=NULL)
	{
		len++;
		p=p->next;
	}


	return len;                  //返回鏈表結點個數,鏈表長度
}

void display(node *head)         //輸出鏈表
{
	node *p;
	p=head->next;                //p重新指向頭結點後的那個結點,即for循環創建的第一個結點
	if(p==NULL)
		cout<<"NULL List";
	while(p!=NULL)               //輸出
	{
		cout<<p->x<<"  ";
		p=p->next;
	}
	cout<<endl;
}

node* search(node *head,int pos)
{
	node *p;
	p=head->next;                //p重新指向頭結點後的那個結點,即for循環創建的第一個結點


	while(--pos)                 //查找,不能用pos--
	{
		if((p=p->next)==NULL)
		{
			cout<<"incorrect position"<<endl;
			break;
		}
			
	}


	if(p!=NULL)
	cout<<p->x<<endl;	
	return p;
}


int main()
{
	node *list;
	list=create(10);
	display(list);
	cout<<"The length of list is: "<<getLength(list)<<endl;
	search(list,1);
	return 0;
}


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