单链表操作实现getelem_【数据结构】单链表的基本操作(C语言
时间: 2023-08-12 22:27:49 浏览: 351
好的,以下是单链表操作实现getelem的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct node {
int data;
struct node* next;
} Node;
// 创建单链表
Node* createList(int arr[], int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 获取单链表指定位置的元素值
int getElem(Node* head, int position) {
int i = 0;
Node* curr = head;
while (curr != NULL && i < position) {
curr = curr->next;
i++;
}
if (curr == NULL) {
printf("Error: position out of range.\n");
return -1;
} else {
return curr->data;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
Node* head = createList(arr, n);
printf("The list: ");
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
printf("The element at position 2 is %d.\n", getElem(head, 2));
printf("The element at position 5 is %d.\n", getElem(head, 5));
return 0;
}
```
输出结果为:
```
The list: 1 2 3 4 5
The element at position 2 is 3.
Error: position out of range.
The element at position 5 is -1.
```
以上代码实现了单链表的基本操作之一:获取指定位置的元素值。在 `getElem` 函数中,我们使用了一个循环遍历链表,依次访问每个节点,直到找到目标位置对应的节点,然后返回该节点的数据值。如果目标位置超出了链表的范围,我们输出错误信息并返回 -1。
阅读全文