将数组的内容,用前插法建立一个带有头节点的单向链表。 #include "stdlib.h" #include "stdio.h" #define N 10 typedef struct list { int data; struct list *next; }NODE; NODE *creat_list(int *a,int n) { } print(NODE *h) //打印链表内容 { NODE *p; p=h->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("\n"); } int main() { int i,j,a[N]={1,13,25,37,9,911,133,415,147,19}; NODE *head; head=creat_list(a,10); print(head); } 使用c语言编写
时间: 2024-03-22 18:38:20 浏览: 121
好的,我知道了。以下是代码实现:
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct list {
int data;
struct list *next;
} NODE;
NODE *creat_list(int *a, int n) {
NODE *head, *p, *q;
head = (NODE *) malloc(sizeof(NODE));
head->next = NULL;
q = head;
for (int i = 0; i < n; ++i) {
p = (NODE *) malloc(sizeof(NODE));
p->data = a[i];
p->next = q->next;
q->next = p;
q = p;
}
return head;
}
void print(NODE *h) {
NODE *p;
p = h->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int i, j, a[N] = {1, 13, 25, 37, 9, 911, 133, 415, 147, 19};
NODE *head;
head = creat_list(a, 10);
print(head);
return 0;
}
这个程序使用前插法将数组的内容建立为一个带有头节点的单向链表,然后打印链表的内容。在 creat_list
函数中,我们首先创建一个头节点,然后遍历数组中的元素,每次创建一个新节点并将其插入到链表的头部。最后返回头节点。在 print
函数中,我们从链表的第二个节点开始遍历,并打印每个节点的数据。
相关推荐















