采用头插法和尾插法创建一个单链表。假设链表中的数据元素均为整数。第一行输入2个整数,第1个为创建方法(1为头插法,2为尾插法),第2个为链表的长度。创建好的单链表,若果为空链表,输出“list is empty!”。C语言
时间: 2023-05-12 12:03:09 浏览: 89
很高兴为您解答问题!以下是使用头插法和尾插法创建单链表的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList(int method, int length) {
Node* head = NULL;
Node* tail = NULL;
int i;
for (i = 0; i < length; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &(newNode->data));
newNode->next = NULL;
if (method == 1) { // 头插法
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
newNode->next = head;
head = newNode;
}
} else if (method == 2) { // 尾插法
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
}
if (head == NULL) {
printf("list is empty!\n");
}
return head;
}
void printList(Node* head) {
if (head == NULL) {
printf("list is empty!\n");
return;
}
printf("链表中的元素为:");
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int method, length;
printf("请输入创建方法(1为头插法,2为尾插法)和链表长度:");
scanf("%d%d", &method, &length);
Node* head = createList(method, length);
printList(head);
return 0;
}
```
如果您有更多问题,欢迎继续提问!
阅读全文