线性表的初始化 求长度末尾添加新节点 任何位置插入一个新节点,删除指定位置的节点,顺序查找节点位置,关键字查找序号,输出所有节点信息c语言
时间: 2024-09-22 11:04:55 浏览: 42
线性表是一种基础的数据结构,通常用于存储一组元素按照一定的顺序排列。在C语言中,我们常见的操作包括初始化、动态增加或删除节点以及搜索节点。
1. **初始化**:
对于数组形式的线性表,可以静态初始化,如`int list[5] = {1, 2, 3, 4, 5};`。对于动态分配的链表,初始化一般通过创建新的节点并设置指针连接,例如:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->data = 0; // 初始化第一个元素
head->next = NULL;
return head;
}
```
2. **求长度**:
对于链表,需要遍历整个链表计算节点数,对于数组则直接用sizeof除以元素大小即可:
```c
size_t listLength(Node* head) {
size_t length = 0;
while (head != NULL) {
length++;
head = head->next;
}
return length;
}
```
3. **末尾添加新节点**:
链表中,在最后一个节点之后添加新节点,首先找到当前列表的尾部:
```c
void append(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
}
```
4. **任意位置插入**:
需要找到目标位置并调整后续节点的指针:
```c
void insertAtPosition(Node** head, int position, int value) {
if (position < 0 || position > listLength(*head)) {
printf("Invalid position.\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (position == 0) {
newNode->next = *head;
*head = newNode;
} else {
Node* prev = *head;
for (int i = 1; i < position; i++) {
prev = prev->next;
}
newNode->next = prev->next;
prev->next = newNode;
}
}
```
5. **删除指定位置的节点**:
删除节点需要考虑头结点和特殊情况:
```c
void deleteNode(Node** head, int position) {
if (position < 0 || position >= listLength(*head)) {
printf("Invalid position.\n");
return;
}
if (position == 0) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
} else {
Node* prev = *head;
for (int i = 1; i < position; i++) {
prev = prev->next;
}
Node* nodeToDel = prev->next;
prev->next = nodeToDel->next;
free(nodeToDel);
}
}
```
6. **顺序查找**:
遍历链表寻找特定值,直到找到或到达末尾:
```c
int findNode(Node* head, int value) {
Node* current = head;
while (current != NULL && current->data != value) {
current = current->next;
}
return current != NULL ? current->data : -1; // 返回节点值或-1表示未找到
}
```
7. **关键字查找序号**:
与顺序查找类似,但在返回值时包含节点的位置:
```c
size_t searchIndex(Node* head, int value) {
Node* current = head;
size_t index = 0;
while (current != NULL && current->data != value) {
current = current->next;
index++;
}
return current != NULL ? index : -1; // 返回节点位置或-1表示未找到
}
8. **输出所有节点信息**:
递归遍历链表打印每个节点的值:
```c
void printList(Node* head) {
if (head == NULL) {
return;
}
printf("%d ", head->data);
printList(head->next);
}
```
阅读全文