C語言連結串列的建立和遍歷
阿新 • • 發佈:2019-02-17
連結串列是一種常見的重要的資料結構。它是動態地進行儲存分配的一種結構。它可以根據需要開闢記憶體單元。連結串列有一個“頭指標”變數,以head表示,它存放一個地址。該地址指向一個元素。連結串列中每一個元素稱為“結點”,每個結點都應包括兩個部分:一為使用者需要用的實際資料,二為下一個結點的地址。因此,head指向第一個元素:第一個元素又指向第二個元素;……,直到最後一個元素,該元素不再指向其它元素,它稱為“表尾”,它的地址部分放一個“NULL”(表示“空地址”),連結串列到此結束。
下面是簡單的程式碼展示:
#include<stdio.h> //定義了 struct Node { int data; struct Node * pNext; }; /* 頭結點:是頭結點是首節點前的那個節點 並不存放資料的資料 頭結點的資料型別和首節點的型別一模一樣 未來方便對連結串列的操作 頭指標:存放頭結點地址的指標變數 首節點:存放第一個有效資料的節點 尾節點:存放最後一個有效資料的節點 */ struct Node * CreateList(void); void TraverseList(struct Node * pHead); int main(void) { struct Node * pHead=NULL;//定義頭指標,用來存放連結串列 pHead=CreateList(); TraverseList(pHead); return 0; } struct Node * CreateList(void) { int len; int i; int val; struct Node * pHead=(struct Node *)malloc(sizeof(struct Node)); if(NULL==pHead) { printf("分配失敗,程式終止!\n"); exit(-1); } struct Node * pTail=pHead; pTail->pNext=NULL; printf("請輸入需要生成的連結節點的個數:len="); scanf("%d",&len); for(i=0;i<len;++i) { printf("請輸入第%d個節點的值:",i+1); scanf("%d",&val); struct Node * pNew=(struct Node *)malloc(sizeof(struct Node)); if(NULL==pNew) { printf("分配失敗,程式終止!\n"); exit(-1); } pNew->data=val; pTail->pNext=pNew; pNew->pNext=NULL; pTail=pNew; } return pHead; } void TraverseList(struct Node * pHead) { struct Node * p=pHead->pNext; if(pHead->pNext==NULL) { printf("連結串列為空!"); } else { while(p!=NULL) { printf("%d",p->data); p=p->pNext; } } }