去年的秋天,用js梳理了一下數據結構。node
那麼這個夏天,一塊兒用C語言來品味一下數據結構之美吧。ios
下面這段程序就是單鏈表的創建函數。數據結構
裏面的細節主要在於建立鏈表中的節點node,而後用指針將這些節點進行銜接。函數
須要注意的是,頭節點的初始化:spa
head=(node*)malloc(sizeof(node));
節點指針的移動:指針
p->next=s; p=s;
以及對於邊界條件的處理:code
head = head->next; p->next = NULL;
總體程序以下:ci
#include <iostream> #include <stdio.h> #include <string.h> #include <conio.h> using namespace std; typedef struct student { int data; struct student *next; }node; node *creat() { node *head,*p,*s; int x,cycle=1; head=(node*)malloc(sizeof(node)); p=head; while(cycle) { cout<<"\n please input the data: "; cin>>x; if(x!=0) { s=(node *)malloc(sizeof(node)); s->data = x; cout<<"\n"<<s->data; p->next=s; p=s; } else { cycle=0; } } head = head->next; p->next = NULL; cout<<head->data; return head; }