鏈表是由許多相同數據類型的數據項按特定排列順序排列而成的線性表。特性是其各個數據項在內存中的排列是不連續且隨機存放的,需要”動態分配內存“時,最適合鏈表的結構設計,可以讓內存運用更具有彈性。
在C語言中,動態分配內存主要使用malloc()與free()函數,定義于頭文件stdlib.h文件中。舉例如下:
#include <stdio.h>#include <stdlib.h>#include <string.h> int main(){ char *str1="Hello World!"; char* str2=(char*)malloc(sizeof(char)*(strlen(str1))); /* 動態分配與str1相同大小的內存空間 */ strcpy(str2,str1);/* 將str1字符串復制到str2字符串 */ C++ 中的動態分配變量,使用new等關鍵字獲取內存地址,用delete釋放內存。代碼片段舉例如下:int* m=new int;*m=50;cout<<"當前指針m所指向的地址:"<<m<<endl;delete m;cout<<"執行delete m 后指針m指向的地址:"<<m<<endl;一個單向鏈表由兩個元素組成,數據字段和指針,指針則指向下一個元素在內存中的地址。 接下來是一段建立學生節點單向鏈表的算法
typedef struct student s_data;s_data *ptr; //access pointer s_data *head;//Chain table pointers_data *new_data;//Pointer to the location of the new elementhead=(s_data*)malloc(sizeof(s_data));ptr=head;ptr->next=NULL;do{ printf("name IDnumber score: "); scanf("%s %s %d",ptr->name,ptr->no,&ptr->score); new_data=(s_data*)malloc(sizeof(s_data));//Add new element ptr->next=new_data; new_data->next=NULL; ptr=ptr->next;}即使用指針運算訪問鏈表中的每個節點。
#include <stdio.h>#include <stdlib.h>int main(){ int select,student_no=0,num=0; float Msum=0,Esum=0; struct student { char name[20]; int Math; int Eng; char no[10]; struct student *next; }; typedef struct student s_data; s_data *ptr; /* 存取指針 */ s_data *head; /* 鏈表頭指針 */ s_data *new_data; /* 新增元素所在位置的指針 */ head = (s_data*) malloc(sizeof(s_data)); /* 建立鏈表頭 */ head->next=NULL; ptr = head; do { printf("(1)新增 (2)離開 =>"); scanf("%d", &select); if (select != 2) { printf("姓名 學號 數學成績 英語成績:"); new_data = (s_data*) malloc(sizeof(s_data)); /* 新增下一個元素 */ scanf("%s %s %d %d",new_data->name,new_data->no,&new_data->Math,&new_data->Eng); ptr->next=new_data; /*存取指針設置為新元素所在位置 */ new_data->next =NULL; /* 下一個元素的next先設置為null */ ptr=ptr->next; num++; } } while (select != 2); ptr = head->next; /* 設置存取指針從頭開始 */ putchar('/n'); while (ptr!= NULL) { printf("姓名:%s/t學號:%s/t數學成績:%d/t英語成績:%d/n", ptr->name,ptr->no,ptr->Math,ptr->Eng); Msum+=ptr->Math; Esum+=ptr->Eng; student_no++; ptr= ptr ->next; /* 將ptr移往下一個元素 */ } printf("---------------------------------------------------------/n"); printf("本鏈表學生數學平均成績:%.2f 英語平均成績:%.2f/n",Msum/student_no,Esum/student_no); system("pause"); return 0;}舉例如下:
struct employee{ int num,score; char name[10]; struct employee *next;};typedef struct employee node;typedef node *link;link findnode(link head,int num){ link ptr; ptr=head; while(ptr!=NULL) { if(ptr->num==num) return ptr; ptr=ptr->next; } return ptr;}link insertnode(link head,link ptr,int num,int score,char name[10]) { link InsertNode; InsertNode=(link)malloc(sizeof(node)); if(!InsertNode) return NULL; InsertNode->num=num; InsertNode->score=score; strcpy(InsertNode->name,name); InsertNode->next=NULL; if(ptr==NULL) /*插入第一個節點*/ { InsertNode->next=head; return InsertNode; } else { if(ptr->next==NULL)/*插入最后一個節點*/ { ptr->next=InsertNode; } else /*插入中間節點*/ { InsertNode->next=ptr->next; ptr->next=InsertNode; } } return head;}新聞熱點
疑難解答