建立并输出两个递增单链表la和lb。 a、 首先要定义单链表的数据结构 b、 编写一个
时间: 2023-08-08 09:01:35 浏览: 40
a、单链表的数据结构可以定义为:
```c
struct Node {
int data;
struct Node* next;
};
```
其中,Node是一个结点,data表示结点的数据部分,next指向下一个结点。
b、下面是一个示例代码,用于建立并输出两个递增单链表la和lb:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表的数据结构
struct Node {
int data;
struct Node* next;
};
// 建立递增的单链表
struct Node* createIncreasingList(int length) {
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < length; i++) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i + 1; // 假设递增的数据从1开始
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 输出单链表中的所有元素
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 建立两个递增的单链表
struct Node* la = createIncreasingList(5); // la为含有5个元素的递增单链表
struct Node* lb = createIncreasingList(10); // lb为含有10个元素的递增单链表
// 输出两个单链表的元素
printList(la);
printList(lb);
return 0;
}
```
此示例中,createIncreasingList函数用于建立递增的单链表,printList函数用于输出单链表中的所有元素。在main函数中,首先调用createIncreasingList函数建立两个递增单链表la和lb,然后通过printList函数分别输出两个单链表的元素。