C++建立一个长度为10的顺序空表
时间: 2023-05-22 08:01:33 浏览: 77
好的,以下是建立一个长度为10的顺序空表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void initList(SeqList *L) {
L->length = 0;
}
int main() {
SeqList L;
initList(&L);
printf("成功建立一个长度为%d的顺序空表\n", MAX_SIZE);
return 0;
}
```
希望这个代码能够帮到你!
相关问题
使用 c++语言创建一个元素为结构体数组的顺序表
可以使用以下代码创建一个元素为结构体数组的顺序表:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int id;
char name[20];
} Student;
typedef struct {
Student data[MAXSIZE];
int length;
} SeqList;
SeqList* createSeqList() {
SeqList* list = (SeqList*)malloc(sizeof(SeqList));
list->length = 0;
return list;
}
void insert(SeqList* list, Student s) {
if (list->length >= MAXSIZE) {
printf("List is full!\n");
return;
}
list->data[list->length] = s;
list->length++;
}
void printList(SeqList* list) {
for (int i = 0; i < list->length; i++) {
printf("ID: %d, Name: %s\n", list->data[i].id, list->data[i].name);
}
}
int main() {
SeqList* list = createSeqList();
Student s1 = {1, "Tom"};
Student s2 = {2, "Jerry"};
insert(list, s1);
insert(list, s2);
printList(list);
return 0;
}
```
这个程序创建了一个名为 SeqList 的结构体,其中包含一个元素为 Student 结构体的数组和一个表示数组长度的整数。使用 createSeqList 函数创建一个空的 SeqList,使用 insert 函数向 SeqList 中插入 Student,使用 printList 函数打印 SeqList 中的 Student。
c++建立长度为n的链表
下面是一个简单的示例,展示如何使用 C++ 建立长度为 n 的链表:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 建立长度为 n 的链表
ListNode* buildList(int n) {
if (n == 0) return NULL;
ListNode* head = new ListNode(0);
ListNode* cur = head;
for (int i = 1; i <= n; i++) {
ListNode* node = new ListNode(i);
cur->next = node;
cur = cur->next;
}
return head->next;
}
// 打印链表
void printList(ListNode* head) {
ListNode* cur = head;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
ListNode* head = buildList(5);
printList(head);
return 0;
}
```
在上面的示例中,我们首先定义了一个 `ListNode` 结构体,用来表示链表节点,包含一个值域 `val` 和一个指向下一个节点的指针 `next`。
然后,我们定义了一个函数 `buildList`,用来建立长度为 n 的链表。在函数中,我们首先创建一个头节点 `head`,然后循环 n 次,创建 n 个节点,并将它们按顺序链接在一起。最后返回头节点的下一个节点,即整个链表的头节点。
最后,我们定义了一个函数 `printList`,用来打印链表。在函数中,我们从头节点开始遍历整个链表,依次输出每个节点的值域。
在 `main` 函数中,我们调用 `buildList` 函数建立了一个长度为 5 的链表,然后调用 `printList` 函数打印了这个链表。