1. 程式人生 > >單鏈表的傳引數的引用

單鏈表的傳引數的引用

#include<stdio.h> 
#include<malloc.h>
#define OK 1
#define ERROR 0
typedef struct LNode
{
	int data;
	struct LNode *next;
	
}LNode,LinkList;

//---------------前插法建立單鏈表;---------------- 
void CreatList_H(LinkList* &head,int n)
{
	int i;LinkList *pnew;
	//先建立頭結點,資料為空;
	head=(LinkList*)malloc(sizeof(LinkList)); 
	head->next=NULL;
	for(i=0;i<n;i++)
	{
		pnew=(LinkList*)malloc(sizeof(LNode));
		scanf("%d",&pnew->data);
		pnew->next=head->next;
		head->next=pnew;
	}
	
}

 

//------------------列印連結串列---------------- 
void PrintList(LinkList *head)
{
	LinkList *item;
	item=head;
	item=item->next;//這一步不是必須要做的,為了跳過頭結點(沒有資料) 
	while(item!=NULL)
	{
		printf("----%d----\n",item->data);
		item=item->next;
	
	}
}

int main()
{
	LinkList *L; 
	LNode e1,e2;
	int n;int e2_data;
//-------------建立列表測試------------ 
	printf("輸入要建立的連結串列結點個數:\n");
	scanf("%d",&n);
	printf("輸入%d個數據:\n",n);
	CreatList_H(L,n);
	printf("\n打印出來看看!\n"); 
	PrintList(L);

	return 0;
}

使用引用是為了不用指向指標的指標,連結串列就可以理解為指標,那麼要作為引數傳遞就要用指向指標的指標——雙重指標,會使得程式設計變複雜。所以使用變數引用  LinkList &,傳地址不用指標就行,上面就是這種方法。還有一種方法是——使用指標作為函式返回型別,定義LinkList * 的返回型別,但是這種方法強迫程式設計師注意接收返回值,不像引用,直接一個函式就行。