C语言单链表实现:增删查操作
#include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node *next; } Node;
typedef struct LinkedList { Node *head; } LinkedList;
void initialize(LinkedList *list) { list->head = NULL; }
void insert(LinkedList *list, int value) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = value; newNode->next = NULL;
if (list->head == NULL)
{
list->head = newNode;
}
else
{
Node *current = list->head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
}
void print(LinkedList *list) { Node *current = list->head; while (current != NULL) { printf('%d ', current->data); current = current->next; } printf(' '); }
int search(LinkedList *list, int value) { Node *current = list->head; int position = 1;
while (current != NULL)
{
if (current->data == value)
{
return position;
}
current = current->next;
position++;
}
return 0;
}
void insertAtPosition(LinkedList *list, int position, int value) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = value; newNode->next = NULL;
if (position == 1)
{
newNode->next = list->head;
list->head = newNode;
}
else
{
Node *current = list->head;
int currentPosition = 1;
while (currentPosition < position - 1 && current != NULL)
{
current = current->next;
currentPosition++;
}
if (current == NULL)
{
printf('Invalid position
'); return; }
newNode->next = current->next;
current->next = newNode;
}
}
void deleteAtPosition(LinkedList *list, int position) { if (position == 1) { Node *temp = list->head; list->head = list->head->next; free(temp); } else { Node *current = list->head; int currentPosition = 1; while (currentPosition < position - 1 && current != NULL) { current = current->next; currentPosition++; }
if (current == NULL || current->next == NULL)
{
printf('Invalid position
'); return; }
Node *temp = current->next;
current->next = current->next->next;
free(temp);
}
}
int main() { LinkedList list; initialize(&list);
int value;
printf('Enter values to insert into linked list (enter -1 to stop): ');
while (scanf('%d', &value) == 1 && value != -1)
{
insert(&list, value);
}
printf('Linked list: ');
print(&list);
int searchValue;
printf('Enter value to search: ');
scanf('%d', &searchValue);
int position = search(&list, searchValue);
if (position == 0)
{
printf('Value not found
'); } else { printf('Value found at position %d ', position); }
int insertValue, insertPosition;
printf('Enter value to insert: ');
scanf('%d', &insertValue);
printf('Enter position to insert: ');
scanf('%d', &insertPosition);
insertAtPosition(&list, insertPosition, insertValue);
printf('Linked list after insertion: ');
print(&list);
int deletePosition;
printf('Enter position to delete: ');
scanf('%d', &deletePosition);
deleteAtPosition(&list, deletePosition);
printf('Linked list after deletion: ');
print(&list);
return 0;
原文地址: http://www.cveoy.top/t/topic/pbZF 著作权归作者所有。请勿转载和采集!