删除链表元素是通过两个指针操作符,一个指向连接位置,另一个指向删除位置
#include <stdlib.h>
#include <stdio.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head;
void Insert(int data)
{
struct Node *Temp = (struct Node *)malloc(sizeof(struct Node));
if (Temp == NULL)
{
printf("Memory allocation failed\n");
return; // 检查内存分配
}
Temp->data = data;
Temp->next = NULL;
if (head == NULL)
{
head = Temp; // 如果链表为空,直接将头指针指向新节点
}
else
{
struct Node *current = head; // 使用临时指针遍历链表
while (current->next != NULL)
{
current = current->next;
}
current->next = Temp; // 将新节点插入到链表末尾
}
}
void Delete(int n)
{
struct Node *Temp = head;
if (Temp == NULL)
{
printf("Memory allocation failed\n");
return; // 检查内存分配
}
if (n == 1)
{
head = Temp->next;
free(Temp);
return;
}
int i;
for (i = 0; i < n - 2; i++) // 大于2,才往后移动
Temp = Temp->next;
struct Node *Temp2 = Temp->next;
Temp->next = Temp2->next;
free(Temp2);
}
void Print()
{
struct Node *temp = head;
printf("List is ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
head = NULL;
// 插入
Insert(1);
Insert(2);
Insert(3);
Insert(4);
Insert(5);
// 删除
Delete(5);
Print();
return 0;
}