C中的鏈表
1. 聲明和初始化
/* 節(jié)點(diǎn)結(jié)構(gòu)和變量聲明: */
struct node {
int value;
struct node *next;
};
struct node *head, *temp;
/* 為新節(jié)點(diǎn)分配空間 */
//推薦分配內(nèi)存語(yǔ)句與判斷語(yǔ)句結(jié)合
if ((temp = (struct node *) malloc(sizeof(struct node))) == NULL) {
printf("Allocation failed.\n");
exit(1);
}
2. 訪問節(jié)點(diǎn)元素
(*temp).value = 47; (*temp).next = NULL;
-
temp->value = 47; temp->next = NULL;
(推薦)
3. 打印鏈表節(jié)點(diǎn)
/* 打印首節(jié)點(diǎn)為h的全部鏈表節(jié)點(diǎn)數(shù)據(jù) */ void print_list(struct node *h) { if (h == NULL) { printf("The list is empty.\n"); } else { printf("Values in the list are:\n"); while (h != NULL) { printf("%d\n", h->value); h = h->next; } } }
4. 搜索鏈表節(jié)點(diǎn)
/* 返回指向搜索到節(jié)點(diǎn)的指針驱富,若沒有返回NULL */
struct node *search_list(struct node *h, int x) {
while (h != NULL) {
if (h->value == x) {
return h;
}
h = h->next;
}
return NULL;
}
5. 插入節(jié)點(diǎn)
- 為什么使用二重指針
struct node **h
:我們需要操作的節(jié)點(diǎn)本身是一個(gè)結(jié)構(gòu)體(用指向堆上內(nèi)存的指針表示*h
马澈、*t
),我們需要指向節(jié)點(diǎn)的指針就是一個(gè)二重指針
/* 創(chuàng)建一個(gè)值為v的新節(jié)點(diǎn),并添加到首節(jié)點(diǎn)為*h箩绍,尾節(jié)點(diǎn)為*t的鏈表尾部 */
void insert_node (struct node **h, struct node **t, int v) {
struct node *temp;
if ((temp = (struct node *)malloc(sizeof(struct node))) == NULL) {
printf("Node allocation failed. \n");
exit(1);
/* 申請(qǐng)內(nèi)存失敗,終止程序 */
}
/* 將v拷貝進(jìn)節(jié)點(diǎn) */
temp->value = v;
temp->next = NULL;
if (*h == NULL) {
/* 如果是空鏈表 */
*h = *t = temp;
} else {
/* 非空鏈表然痊,添加在*t尾部 */
(*t)->next = temp;
*t = (*t)->next;
}
}
5. 使用typedef來(lái)簡(jiǎn)化
typedef struct node {
int value;
struct node *next;
} NODE, *PTRNODE;
在以上聲明中:
- NODE 表示struct node
- PTRNODE 表示struct node *
- eg.
NODE x;
PTRNODE head, tail;