#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} ListNode;
void InitList(ListNode **head) {
*head = NULL;
}
int Insert(ListNode **head, int pos, int elem) {
ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
if (!newNode) {
printf("内存分配失败\n");
return 0;
}
newNode->data = elem;
if (pos == 1) {
newNode->next = *head;
*head = newNode;
} else {
ListNode *p = *head;
int i = 1;
while (p && i < pos - 1) {
p = p->next;
i++;
}
if (!p || i > pos - 1) {
printf("插入位置非法\n");
free(newNode);
return 0;
}
newNode->next = p->next;
p->next = newNode;
}
return 1;
}
int Delete(ListNode **head, int pos) {
if (pos < 1 || !(*head)) {
printf("删除位置非法或链表为空\n");
return 0;
}
ListNode *temp;
if (pos == 1) {
temp = *head;
*head = (*head)->next;
} else {
ListNode *p = *head;
int i = 1;
while (p && i < pos - 1) {
p = p->next;
i++;
}
if (!p || !(p->next) || i > pos - 1) {
printf("删除位置非法\n");
return 0;
}
temp = p->next;
p->next = temp->next;
}
free(temp);
return 1;
}
void PrintList(ListNode *head) {
printf("单链表元素为:");
ListNode *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
ListNode *head;
InitList(&head);
Insert(&head, 1, 10);
Insert(&head, 2, 20);
Insert(&head, 3, 30);
Insert(&head, 4, 40);
Insert(&head, 5, 50);
Insert(&head, 6, 60);
printf("插入元素后的单链表:\n");
PrintList(head);
Delete(&head, 2);
printf("删除元素后的单链表:\n");
PrintList(head);
return 0;
}