单链表基本操作的实现 用c语言
时间: 2023-05-22 19:05:08 浏览: 108
可以实现单链表基本操作的 C 语言代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
} Node;
void initList(Node** head)
{
*head = (Node*)malloc(sizeof(Node));
(*head)->next = NULL;
}
int getListLength(Node* head)
{
int length = 0;
Node* p = head->next;
while (p != NULL)
{
length++;
p = p->next;
}
return length;
}
void addNode(Node* head, int data)
{
Node* p = head;
while (p->next != NULL)
{
p = p->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
p->next = newNode;
}
void insertNode(Node* head, int index, int data)
{
if (index < 0 || index > getListLength(head))
{
printf("Index error\n");
return;
}
Node* p = head;
for (int i = 0; i < index; i++)
{
p = p->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
}
void deleteNode(Node* head, int index)
{
if (index < 0 || index > getListLength(head) - 1)
{
printf("Index error\n");
return;
}
Node* p = head;
for (int i = 0; i < index; i++)
{
p = p->next;
}
Node* deletedNode = p->next;
p->next = deletedNode->next;
free(deletedNode);
}
int getNodeData(Node* head, int index)
{
if (index < 0 || index > getListLength(head) - 1)
{
printf("Index error\n");
return -1;
}
Node* p = head->next;
for (int i = 0; i < index; i++)
{
p = p->next;
}
return p->data;
}
int main()
{
Node* head;
initList(&head);
addNode(head, 1);
addNode(head, 2);
insertNode(head, 2, 3);
deleteNode(head, 1);
for (int i = 0; i < getListLength(head); i++)
{
printf("%d ", getNodeData(head, i));
}
return 0;
}
阅读全文