实现带头结点的单链表的建立、求长度,取元素、修改元素、插入、删除等单链表的基本操作。c语言代码
时间: 2023-06-01 18:02:03 浏览: 138
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
LinkedList createLinkedList() {
LinkedList head = (LinkedList)malloc(sizeof(Node));
head->next = NULL;
return head;
}
int length(LinkedList head) {
int len = 0;
Node* p = head->next;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
Node* getElement(LinkedList head, int index) {
if (index < 0 || index >= length(head)) {
printf("Invalid index\n");
return NULL;
}
Node* p = head->next;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
return p;
}
void modifyElement(LinkedList head, int index, int value) {
Node* p = getElement(head, index);
if (p != NULL) {
p->data = value;
}
}
void insertElement(LinkedList head, int index, int value) {
if (index < 0 || index > length(head)) {
printf("Invalid index\n");
return;
}
Node* p = head;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = p->next;
p->next = newNode;
}
void deleteElement(LinkedList head, int index) {
if (index < 0 || index >= length(head)) {
printf("Invalid index\n");
return;
}
Node* p = head;
int i = 0;
while (p->next != NULL && i < index) {
p = p->next;
i++;
}
Node* q = p->next;
p->next = q->next;
free(q);
}
void printLinkedList(LinkedList head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroyLinkedList(LinkedList head) {
Node* p = head;
while (p != NULL) {
Node* q = p;
p = p->next;
free(q);
}
}
int main() {
LinkedList head = createLinkedList();
insertElement(head, 0, 1);
insertElement(head, 1, 2);
insertElement(head, 2, 3);
printf("Length: %d\n", length(head));
printLinkedList(head);
modifyElement(head, 1, 4);
printLinkedList(head);
insertElement(head, 1, 5);
printLinkedList(head);
deleteElement(head, 2);
printLinkedList(head);
destroyLinkedList(head);
return 0;
}
```
阅读全文