单链表节点类型: struct person { int age; char *name; struct person *next; }; a. 实现单链表头插法(封装成函数) b. 实现单链表尾插法(封装成函数) c. 实现单链表查看函数 d. 实现单链表的排序 e. 实现单链表的转置(逆序)
时间: 2023-05-24 15:01:28 浏览: 107
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;
}
阅读全文