鏈表:
鏈表的組成其實很簡單,就是由很多結點組成的。
一個結點包含數據域和指針域,數據域用來存放數據,指針域負責指向其他結點,起到鏈接的作用。
創建鏈表:
其實創建一個鏈表也很簡單,在我看來,可以分爲以下幾步:
1.創建頭結點。(命名爲:head)
2.在創建一個結點用來保存每次插入的結點.(命名爲:p)
3.循環創建一般結點。(命名爲:s)
4.將創建的結點與已有的結點鏈接起來!
5.遍歷鏈表,輸出數據。
需要注意的是:
1.創建結點時一定不要忘了給它分配內存空間;
2.創建的所有結點都應該是指針型的結構體;
3.鏈表一定要有“尾”。
代碼如下:
因爲我覺得尾插法相對頭插更容易理解,所以先用尾插法向你們演示一番。
//尾插法建立鏈表:
#include <stdio.h>
#include <stdlib.h>//裏面包含了malloc函數
struct LinkList//創建結構體
{
int data;//數據域,用來保存數據。
struct LinkList* next;//指針域,用來連接其他結點。
};
int main(void)
{
struct LinkList* head = (struct LinkList*)malloc(sizeof(struct LinkList));//創建頭結點,並分配內存,需要的內存大小就是結構體的大小。別忘了在malloc前進行強制類型轉換。(struct LinkList*)
head->next = NULL;//頭結點指針初始化
struct LinkList* p = (struct LinkList*)malloc(sizeof(struct LinkList));//創建p結點,並分配內存
p = head;//p結點指針賦值爲頭結點
int n;//保存鏈表長度,即結點的個數。
printf("請輸入鏈表長度:\n");
scanf("%d", &n);
printf("輸入數據:\n");
for (int i = 0; i < n; i++)//循環創建結點
{
struct LinkList* s = (struct LinkList*)malloc(sizeof(struct LinkList));//創建s結點,並分配內存
scanf("%d", &s->data);//給s結點賦值。
//尾插法建立鏈表
p->next = s;//因爲插完第一個結點後用p保存了上一個結點,所以再插結點時應該插在p節點後面,這就是尾插。
s->next = NULL;//別忘了讓插在尾部的s結點的指針指向NULL。
p = s;//p結點保存剛纔的s結點;以保證p始終爲鏈表的最後一個節點
}//至此,鏈表的創建已經完成了。
p = head;//讓p指針從"頭"開始。
while (p->next != NULL)//如果p的下一個結點不爲NULL,也就是說如果p結點後還有節點存在,那就輸出p後面結點中保存的數據。
{
printf("%-5d", p->next->data);
p = p->next;//p結點後移
}
printf("\n");
return 0;
}//至此完成了鏈表的遍歷輸出。
代碼運行結果:
好!接下來就是頭插法建立鏈表了,同樣,頭插法與尾插法一般無二,所以廢話不多說,直接上代碼!
//頭插法建立鏈表:
#include <stdio.h>
#include <stdlib.h>//裏面包含了malloc函數
struct LinkList//創建結構體
{
int data;//數據域,用來保存數據。
struct LinkList *next;//指針域,用來連接其他結點。
};
int main(void) {
struct LinkList *head = (struct LinkList *) malloc(
sizeof(struct LinkList));//創建頭結點,並分配內存,需要的內存大小就是結構體的大小。別忘了在malloc前進行強制類型轉換。(struct LinkList*)
head->next = NULL;//頭結點指針初始化
struct LinkList *p;
int n;//保存鏈表長度,即結點的個數。
printf("請輸入鏈表長度:\n");
scanf("%d", &n);
printf("輸入數據:\n");
for (int i = 0; i < n; i++)//循環創建結點
{
struct LinkList *s = (struct LinkList *) malloc(sizeof(struct LinkList));//創建s結點,並分配內存
scanf("%d", &s->data);//給s結點賦值。
//頭插法建立鏈表
s->next = head->next; //將鏈表除鏈表頭的所有節點連接在新建節點之後
head->next = s;//在讓頭結點指向新節點 注意:和上一語句順序不能顛倒
}//至此,鏈表的創建已經完成了。
p = head;//讓p指針從"頭"開始。
while (p->next != NULL)//如果p的下一個結點不爲NULL,也就是說如果p結點後還有節點存在,那就輸出p後面結點中保存的數據。
{
printf("%-5d", p->next->data);
p = p->next;//p結點後移
}
printf("\n");
return 0;
}//至此完成了鏈表的遍歷輸出。
程序運行結果: