本程序设非空单向链表,且数据域不重复,删除关键字
#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct node {
int date;
struct node * next;
}ElemSN;
//创建单向链表
ElemSN * CreateLink(int a[])
{
ElemSN * h, *tail, *p;
int i = 1;
h = tail = (ElemSN *)malloc(sizeof(ElemSN));
h->date = a[0];
h->next = NULL;
for (i; i < N; i++)
{
p = (ElemSN *)malloc(sizeof(ElemSN));
p->date = a[i];
p->next = NULL;
tail->next = p;
tail = p;
}
return h;
}
//输出单向链表
void PrintLink(ElemSN * h)
{
ElemSN * p;
for (p = h; p != NULL; p = p->next)
{
printf("%d\t", p->date);
}
}
ElemSN * DelsingleNode(ElemSN *h,int key)
{
ElemSN *p, *q;
for (p = h; p&&p->date - key; q = p, p = p->next);
if (!p)
printf("not find");
else
{
if (!(p - h))
h = h->next;
else
q->next = p->next;
free(p);
p = NULL;
}
return h;
}
int main()
{
int a[6] = { 3,2,5,8,4,7 };
int key;
ElemSN * head, *Pkey;
//创建单向链表
head = CreateLink(a);
printf("输入要删除的值\n");
scanf("%d", &key);
//删除节点
head = DelsingleNode(head, key);
//输出节点
PrintLink(head);
printf("\n");
}
节点