将两个函数printFor(),printRev()添加到程序13.7 pgm13-7.c中,该程序向前打印链接列表的元素,并使用递归进行反向顺序。使用C语言进行编写
时间: 2024-04-29 19:25:59 浏览: 77
好的,以下是程序13.7 pgm13-7.c 的修改版,已经添加了两个函数printFor()和printRev(),实现了向前打印链接列表的元素并使用递归进行反向顺序打印:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printFor(struct Node *head) {
printf("Forward elements: ");
while(head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void printRev(struct Node *head) {
if(head == NULL) {
return;
}
printRev(head->next);
printf("%d ", head->data);
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printFor(head);
printRev(head);
free(head);
free(second);
free(third);
return 0;
}
```
需要说明的是,printFor()函数使用了while循环来从头至尾遍历链接列表并打印每个节点的数据。而printRev()函数使用了递归来从尾到头遍历链接列表并打印每个节点的数据,因此它的实现比较巧妙。
阅读全文