链表以及函数的声明,声明在node.h文件中
#ifndef _NODE_H
struct node
{
int data;
struct node *next;
};
int isEmpty(node* L);
node* Find(int x, node* L);
int isLast(node *p, node *L);
node* findPre(int x, node* L);
void del(int x, node* L);
void insert1(int x, node *P);
void insert2(int x, node* P);
void delist(node *L);
void print(node* L);
#endif
具体实现,在cpp文件中
#include<stdio.h>
#include<stdlib.h>
#include"node.h"
int isEmpty(node* L)//链表是否为空
{
return L->next == NULL;
}
node* Find(int x, node* L)//寻找某一个元素
{
node *p;
p = L->next;
while (p != NULL&&p->data != x)
p = p->next;
return p;
}
int isLast(node *p, node *L)//是否是最后一个元素
{
return p->next == NULL;
}
node* findPre(int x, node* L)//寻找某一个节点的前一个节点
{
node *p;
p = L;
while (p->next != NULL&&p->next->data != x)
p = p->next;
return p;
}
void del(int x, node* L)//删除某一个节点
{
node *p, *q;
p = findPre(x, L);
if (!isLast(p, L))
{
q = p->next;
p->next = q->next;
free(q);
}
}
void insert1(int x, node *P)//插入节点,使用头插法
{
node* tmp;
tmp = (node*)malloc(sizeof(struct node));
tmp->data = x;
tmp->next = P->next;
P->next = tmp;
}
void insert2(int x, node* P)//插入节点,使用尾插法
{
node *last,*tmp;
last = P;
tmp = (node*)malloc(sizeof(struct node));
tmp->data = x;
while (last->next != NULL)
last = last->next;
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
void delist(node *L)//删除整个链表
{
node *p, *tmp;
p = L->next;
L->next = NULL;
while (p != NULL)
{
tmp = p->next;
free(p);
p = tmp;
}
}
void print(node* L)
{
node *p;
p = L->next;
while (p != NULL)
{
printf_s("%d ", p->data);
p = p->next;
}
}
int main()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
int n, i, tmp;
while (scanf_s("%d", &n) != EOF)
{
for (i = 0; i < n; i++)
{
scanf_s("%d", &tmp);
insert2(tmp, head);
}
print(head);
printf_s("\n请输入要删除的元素:");
scanf_s("%d", &tmp);
del(tmp, head);
print(head);
}
getchar();
return 0;
}