单链表节点类型: struct person { int age; char *name; struct person *next; }; a. 实现单链表头插法
时间: 2023-05-24 20:01:53 浏览: 101
:首先需要创建一个头节点,然后遍历单链表,在头节点之后插入新节点。以下是实现代码:
struct person *head = NULL; // 头节点初始化为空
// 头插法
void insert_head(int age, char *name) {
struct person *node = (struct person*)malloc(sizeof(struct person));
node->age = age;
node->name = name;
node->next = head; // 新节点的下一个节点为头节点
head = node; // 新节点成为新的头节点
}
注意需要进行内存分配,且要注意节点之间的指向关系。
相关问题
单链表节点类型: struct person { int age; char *name; struct person *next; }; a. 实现单链表头插法(封装成函数) b. 实现单链表尾插法(封装成函数) c. 实现单链表查看函数 d. 实现单链表的排序 e. 实现单链表的转置(逆序)
a. 实现单链表头插法的代码如下:
void headInsert(struct person **head, int age, char *name) {
struct person *newNode = (struct person *)malloc(sizeof(struct person));
newNode->age = age;
newNode->name = name;
newNode->next = *head;
*head = newNode;
}
b. 实现单链表尾插法的代码如下:
void tailInsert(struct person **head, int age, char *name) {
struct person *newNode = (struct person *)malloc(sizeof(struct person));
newNode->age = age;
newNode->name = name;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct person *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
c. 实现单链表查看函数的代码如下:
void displayList(struct person *head) {
if (head == NULL) {
printf("List is empty\n");
} else {
struct person *p = head;
while (p != NULL) {
printf("%d %s\n", p->age, p->name);
p = p->next;
}
}
}
d. 实现单链表的排序的代码如下:
void sortList(struct person **head) {
if (*head == NULL) {
return;
}
int swapped;
struct person *ptr1 = *head;
struct person *lptr = NULL;
do {
swapped = 0;
while (ptr1->next != lptr) {
if (ptr1->age > ptr1->next->age) {
swapNodes(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
ptr1 = *head;
} while (swapped);
}
void swapNodes(struct person *a, struct person *b) {
int tmpAge = a->age;
char *tmpName = a->name;
a->age = b->age;
a->name = b->name;
b->age = tmpAge;
b->name = tmpName;
}
e. 实现单链表的转置(逆序)的代码如下:
void reverseList(struct person **head) {
struct person *prev = NULL;
struct person *current = *head;
struct person *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
单链表节点类型: struct person { int age; char *name; struct person *next; }; 进行链表遍历
可以使用一个 while 循环,从链表的头节点开始依次遍历每一个节点,直到遍历到最后一个节点即可:
```
void traverse_linked_list(struct person *head) {
struct person *current = head;
while (current != NULL) {
printf("Age: %d, Name: %s\n", current->age, current->name);
current = current->next;
}
}
```
请注意这是一个C语言实现的链表遍历函数。
阅读全文
相关推荐














