數據結構之: 線性鏈表

最近看了數據結構,打算寫一個小的總結,後續一系列的,慢慢都會有,把自己寫過的代碼記錄一下,也督促自己不要半途而廢,就醬~

一  線性鏈表

單鏈表大家都很熟,直接上代碼:(參考pointers on C 一書di12章)



while ((current=*linkP)!=NULL &&
current->value < new_valu其中部分涉及指針的指針,比較蛋疼,說一下
假如有這樣的表達式:int a = 12;int *b = &a; int **c =  &b;
那麼就有:
表達式 相當的表達式
a 12
b &a
*b a, 12
c &b
*c b,&a
**c *b, a, 12
在while循環中我用到了
while ((current=*linkP)!=NULL &&
current->value < new_value)
{
linkP=¤t->link;
}
current=*linkP這個句子,*linkP相當於下一個node的地址,所以這是讓current指向了linkP當前指向節點的下一個節點,current 是指向當前節點的指針,linkP是指向當前節點的link字段的指針或者指向頭指針的指針,程序有任何錯誤,可以在評論裏告知,另,CSDN編輯格式爲什麼在插入代碼後切不迴文字模式了?



#include <STDIO.H>
#include <stdlib.h>

typedef struct Node
{
	struct Node *link;
	int value;
}Node;

#define  FALSE 0
#define  TRUE  1

int InsertAll( Node** linkP,int new_value)
{
	 Node *current;
	 Node *new1;

	//尋找插入的位置
	while ((current=*linkP)!=NULL &&
		current->value < new_value)
	{
		linkP=&currentt->link;
	}
	new1 =(Node*)malloc(sizeof(Node));
	if( new1==NULL)
	{
		return FALSE;
	}
	new1->value=new_value;
	new1->link = current;
	*linkP = new1;
	return TRUE;

}

int deleteAll(Node** link,int value)
{
	Node *current;
    while ((current=*link)!=NULL &&
		current->value != value)
	{
		link=&currentt->link;
	}
	*link=current->link;
	free(current);
	return 0;
}

int GetElem_Value(Node* link,int value)
{
	int i=1;
	while((link)!=NULL)
	{
		if (link->value==value)
		{
			printf("find! %d\n",i);
			return 0;
		}
		++i;
		link=link->link;
	}
	printf("ERROR:don not find \n");
	return -1;
}

int GetElem_Int(Node* link,int position)
{
	int i=1;
	while((link)!=NULL)
	{
		if (i==position)
		{
			printf("find! %d %d\n",i,link->value);
			return 0;
		}
		++i;
		link=link->link;
	}
	printf("ERROR:don not find \n");
	return -1;
}
int PrintLinklist(Node* link)
{
	while ((link)!=NULL)
	{
		printf("%d\n",link->value);
		link=link->link;
	}
	return 0;

}


int main()
{
	Node **linklist;
	Node *link;
	Node first;
	first.link=NULL;
	first.value=3;
	link=&first;
	linklist=&link;

	InsertAll(linklist,10);
	PrintLinklist(link);
   // GetElem_Value(link,10);
	//GetElem_Int(link,1);
	//GetElem_Int(link,2);
	//GetElem_Int(link,3);
	deleteAll(linklist,10);
	PrintLinklist(link);
    return 0;

}



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