一、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 <= 10; i++){
p = (struct structnode *)malloc(sizeof(struct structnode));
p->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 < pos; i++){
q = p;
p = p->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 < pos; i++){
q = p;
p = p->next;
}
q->next = p->next;
free(p);
}
以上是一个在链表中删除节点的函数。我们通过指针在链表中找到要删除的节点,并将其从链表中剔除。