C语言创建两个单链表的代码
时间: 2024-05-03 11:20:33 浏览: 5
以下是 C 语言创建两个单链表的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
typedef struct node Node;
Node *createList(int array[], int n) {
Node *head = NULL;
Node *tail = NULL;
for (int i = 0; i < n; i++) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = array[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void traverseList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int array1[] = {1, 3, 5, 7, 9};
int array2[] = {2, 4, 6, 8, 10};
Node *list1 = createList(array1, 5);
Node *list2 = createList(array2, 5);
traverseList(list1);
traverseList(list2);
return 0;
}
```