//设head指向一个非空单向链表,其数据域的值不重复,在链表中删除关键字值为key的结点
//思想:跑链表,找到停下,做删除操作;
//其中删除操作分为头结点删除和中间尾结点删除
//头结点要注意移头,中间尾结点要注意挂链
//1.0
#include<stdio.h>
#include<stdlib.h>
#define N 6
typedef struct odd{
int data;
struct odd *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*tail;
h=tail=(ElemSN *)malloc(sizeof(ElemSN));
h->data=a[0];
h->next=NULL;
for(int i=1;i<N;i++){
tail=tail->next=(ElemSN *)malloc(sizeof(ElemSN));
tail->data=a[i];
tail->next=NULL;
}
return h;
}
ElemSN *Delone(ElemSN *h,int key)
{
//查找
ElemSN *p,*q;
for(p=h;p&&p->data!=key;q=p,p=p->next);
if(!p) printf("not found!\n"); //跑完没有要找的值
else {
if(p==h){//删除头结点
h=h->next;
free(p);
p=NULL;
}
else {//删除中间尾结点
q->next=p->next;
free(p);
p=NULL;
}
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p;p=p->next){
printf("%d",p->data);
}
}
int main()
{
int i,key;
int a[6]={3,2,5,8,4,7};
ElemSN *head=NULL,*pkey;
//创建链表
head=Createlink(a);
//输入要删除的元素
scanf("%d",&key);
//返回新的头结点
pkey=Delone(head,key);
Printlink(pkey);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define N 6
typedef struct odd{
int data;
struct odd *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*tail;
h=tail=(ElemSN *)malloc(sizeof(ElemSN));
h->data=a[0];
h->next=NULL;
for(int i=1;i<N;i++){
tail=tail->next=(ElemSN *)malloc(sizeof(ElemSN));
tail->data=a[i];
tail->next=NULL;
}
return h;
}
ElemSN *Delone(ElemSN *h,int key)
{
//查找
ElemSN *p,*q;
for(p=h;p&&p->data!=key;q=p,p=p->next);
if(!p) printf("not found!\n"); //跑完没有要找的值
else {
if(p!=h){//删除中间尾结点
q->next=p->next;
}
else {//删除头结点
h=h->next;
}
free(p);
p=NULL;
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p;p=p->next){
printf("%d",p->data);
}
}
int main()
{
int i,key;
int a[6]={3,2,5,8,4,7};
ElemSN *head=NULL,*pkey;
//创建链表
head=Createlink(a);
//输入待删元素
scanf("%d",&key);
pkey=Delone(head,key);
Printlink(pkey);
return 0;
}
//值重复时,删除值为key的结点
#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct odd{
int data;
struct odd *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*tail;
h=tail=(ElemSN *)malloc(sizeof(ElemSN));
h->data=a[0];
h->next=NULL;
for(int i=1;i<N;i++){
tail=tail->next=(ElemSN *)malloc(sizeof(ElemSN));
tail->data=a[i];
tail->next=NULL;
}
return h;
}
ElemSN *Delthekey(ElemSN *h,int key)
{
ElemSN *p,*q;
p=h;
while(p){
if(p->data!=key){//联动
q=p;
p=p->next;
}
else{//删
//头删
if(p==h){
h=h->next;
free(p);
p=h;//避免连着的重复待删值
}
//删中间尾
else{
q->next=p->next;
free(p);
p=q->next;//避免连着的重复待删值
}
}
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p;p=p->next){
printf("%6d",p->data);
}
}
int main()
{
int a[N],i,key;
ElemSN *head=NULL;
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
printf("请输入key的值:");
scanf("%d",&key);
//正向建链
head=Createlink(a);
head=Delthekey(head,key);
//输出
Printlink(head);
return 0;
}