线性表L(1,2,3,4,5),用头插法建立相应的单链表
时间: 2024-05-02 22:23:14 浏览: 28
好的,我可以回答您的问题。针对您的问题,可以按照如下步骤来实现:
1. 定义一个单链表的结构体,包括一个数据域和一个指针域
2. 定义一个指向单链表的头指针,初始化为空
3. 按照头插法的思路,从后往前遍历线性表L,依次将每个元素插入到单链表的头部
4. 遍历完成后,头指针指向单链表的头部,即可完成建立相应的单链表
下面是示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void createList(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void printList(struct Node* head) {
struct Node* currentNode = head;
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
}
int main() {
int L[] = {1, 2, 3, 4, 5};
int len = sizeof(L) / sizeof(L[0]);
struct Node* head = NULL;
for (int i = len - 1; i >= 0; i--) {
createList(&head, L[i]);
}
printList(head);
return 0;
}
```
希望能对您有所帮助。如有其他问题,您可以随时提出。