采用头插法和尾插法创建一个单链表。假设链表中的数据元素均为整数。
时间: 2023-05-12 17:03:02 浏览: 250
单链表(头插法,尾插法)
头插法创建单链表的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createListByHeadInsert(int arr[], int n) {
Node *head = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = arr[i];
node->next = head;
head = node;
}
return head;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
Node *head = createListByHeadInsert(arr, n);
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}
```
尾插法创建单链表的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createListByTailInsert(int arr[], int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
Node *head = createListByTailInsert(arr, n);
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}
```
阅读全文