一、structnode 的定義
struct structnode{
int data;
struct structnode *next;
};
structnode 是一個結構體類型,包含兩個成員變量 data 和 next。其中,data 是當前節點存儲的數據,next 是指向下一個節點的指針。
當我們需要用鏈表來描述一組數據時,可以通過定義結構體來實現。在這個結構體中,我們可以將數據作為一個成員變量,而鏈表的節點則是結構體本身。
二、structnode 的創建
struct structnode *create(int n){
struct structnode *head, *p, *q;
int i;
head = (struct structnode *)malloc(sizeof(struct structnode));
head->data = n;
q = head;
for(i = 2; i data = i * n;
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
以上是一個創建鏈表的函數。我們通過循環來依次創建鏈表中的每個節點,將每個節點串聯起來,最後返回鏈表的頭節點。
三、structnode 的遍歷
void traverse(struct structnode *head){
struct structnode *p;
p = head;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
}
以上是一個遍歷鏈表的函數。我們通過指針來依次訪問鏈表中的每個節點,輸出節點存儲的數據。
四、structnode 的插入
void insert(struct structnode *head, int pos, int value){
struct structnode *p, *q;
int i;
p = head;
for(i = 1; i next;
}
q->next = (struct structnode *)malloc(sizeof(struct structnode));
q->next->data = value;
q->next->next = p;
}
以上是一個在鏈表中插入節點的函數。我們通過指針在鏈表中找到要插入的位置,並將新節點的指針插入到鏈表中。
五、structnode 的刪除
void delete(struct structnode *head, int pos){
struct structnode *p, *q;
int i;
p = head;
for(i = 1; i next;
}
q->next = p->next;
free(p);
}
以上是一個在鏈表中刪除節點的函數。我們通過指針在鏈表中找到要刪除的節點,並將其從鏈表中剔除。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/189883.html
微信掃一掃
支付寶掃一掃