使用c语言实现单链表,包括初始化单链表、判断单链表是否为空、获取单链表长度、 在单链表末尾插入节点、在单链表指定位置插入节点、删除单链表指定位置的节点、 获取单链表指定位置的节点值、修改单链表指定位置的节点值、输出单链表等操作。并在主函数中进行测试
时间: 2023-07-10 07:19:40 浏览: 49
好的,我会为您介绍如何使用 C 语言实现单链表。首先,我们需要定义一个结构体来表示每个节点:
```c
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域
} Node;
```
接下来,我们需要实现单链表的各种操作:
1. 初始化单链表
```c
void initList(Node** head) {
*head = NULL;
}
```
2. 判断单链表是否为空
```c
int isEmpty(Node* head) {
return head == NULL;
}
```
3. 获取单链表长度
```c
int getLength(Node* head) {
int len = 0;
Node* p = head;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
```
4. 在单链表末尾插入节点
```c
void insertAtEnd(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
```
5. 在单链表指定位置插入节点
```c
void insertAtPos(Node** head, int pos, int data) {
if (pos < 1 || pos > getLength(*head) + 1) {
printf("Invalid position!\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (pos == 1) {
newNode->next = *head;
*head = newNode;
} else {
Node* p = *head;
for (int i = 1; i < pos - 1; i++) {
p = p->next;
}
newNode->next = p->next;
p->next = newNode;
}
}
```
6. 删除单链表指定位置的节点
```c
void deleteAtPos(Node** head, int pos) {
if (pos < 1 || pos > getLength(*head)) {
printf("Invalid position!\n");
return;
}
if (pos == 1) {
Node* p = *head;
*head = (*head)->next;
free(p);
} else {
Node* p = *head;
for (int i = 1; i < pos - 1; i++) {
p = p->next;
}
Node* q = p->next;
p->next = q->next;
free(q);
}
}
```
7. 获取单链表指定位置的节点值
```c
int getValueAtPos(Node* head, int pos) {
if (pos < 1 || pos > getLength(head)) {
printf("Invalid position!\n");
return -1;
}
Node* p = head;
for (int i = 1; i < pos; i++) {
p = p->next;
}
return p->data;
}
```
8. 修改单链表指定位置的节点值
```c
void setValueAtPos(Node* head, int pos, int data) {
if (pos < 1 || pos > getLength(head)) {
printf("Invalid position!\n");
return;
}
Node* p = head;
for (int i = 1; i < pos; i++) {
p = p->next;
}
p->data = data;
}
```
9. 输出单链表
```c
void printList(Node* head) {
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
最后,在主函数中进行测试:
```c
int main() {
Node* head;
initList(&head);
printf("Length: %d\n", getLength(head));
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
printf("Length: %d\n", getLength(head));
printList(head);
insertAtPos(&head, 2, 4);
printf("Length: %d\n", getLength(head));
printList(head);
deleteAtPos(&head, 3);
printf("Length: %d\n", getLength(head));
printList(head);
printf("Value at position 2: %d\n", getValueAtPos(head, 2));
setValueAtPos(head, 2, 5);
printf("Value at position 2: %d\n", getValueAtPos(head, 2));
printList(head);
return 0;
}
```
输出结果为:
```
Length: 0
Length: 3
1 2 3
Length: 4
1 4 2 3
Length: 3
1 4 3
Value at position 2: 4
Value at position 2: 5
1 5 3
```