按照题意,使用单链表来解决这道问题。
#include <stdio.h>
#include <stdlib.h>
typedef struct Linkedlist {
int val;
struct Linkedlist* next;
} Linkedlist;
/* 创建节点*/
Linkedlist* LLCreateNode(int val) {
Linkedlist* node = (Linkedlist*)malloc(sizeof(Linkedlist));
if (node == NULL) {
return NULL;
}
node->val = val;
node->next = NULL;
return node;
}
/*在指定值的节点插入新节点*/
void LLInsertbyValue(Linkedlist* L, int val, int preval) {
while (L) {
if (L->val == preval) {
Linkedlist* temp = LLCreateNode(val);
temp->next = L->next;
L->next = temp;
return;
}
L = L->next;
}
}
void LLDeletebyValue(Linkedlist* L, int val) {
Linkedlist* cur = L;
if (cur -> val == val && cur->next) { // 删除头节点
cur ->val = cur->next->val;
cur->next = cur->next->next;
return;
}
while (cur->next) { // 删除目标节点
if (cur->next->val == val) {
Linkedlist* temp = cur->next;
cur->next = temp->next;
free(temp);
return;
}
cur = cur->next;
}
return; // 没有目标节点
}
void LLprint(Linkedlist *L){
Linkedlist *head = L;
while(head){
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
Linkedlist* L = NULL;
int num = 0;
int val, preval;
if (scanf("%d %d", &num, &val) != EOF) {
L = LLCreateNode(val);
int i = 1;
while (i < num && scanf("%d %d", &val, &preval) != EOF) { // 插入节点
LLInsertbyValue(L, val, preval);
i++;
}
if(scanf("%d", &val) != EOF){ // 删除节点
LLDeletebyValue(L, val);
}
LLprint(L); // 输出
}
return 0 ;
}

京公网安备 11010502036488号