设有一有序序列,从键盘输入一个数,判别是否在序列中,如果不在输出“NO”,否则,将它从序列中删除它,并输出删除后的序列。
#include<iostream>
using namespace std;
struct node
{
int date;
node *next;
};
typedef node *link;
int main()
{
int n;
int num_[8] = {1,2,3,4,5,6,7,8};
//建立链表
link p,q;
link head = new node;
head->date = num_[0];
head->next = NULL;
p = head;
for(int i = 1; i<8; i++)
{
q = new node;
q->date = num_[i];
q->next = NULL;
p->next = q;
p = q;
}
p = head;
while(p!=NULL)
{
cout<<p->date<<ends;
p = p->next;
}
cout<<endl<<"输入要删除的数"<<endl;
while(scanf("%d",&n)!=EOF)
{
bool flag = false;
p = head;
if(head->date == n)
{
flag = true;
head = p->next;
p = head;
cout<<"输出新的序列: ";
while(p != NULL)
{
cout<<p->date<<ends;
p = p->next;
}
cout<<endl;
}
else
{
q = p;
while(q->next != NULL)
{
q = p->next;
if(q->date == n)
{
flag = true;
p->next = q->next;
p = head;
cout<<"输出新的序列: ";
while(p != NULL)
{
cout<<p->date<<ends;
p = p->next;
}
cout<<endl;
break;
}
p = q;
}
}
if(flag == false)
cout<<"NO"<<endl;
cout<<"输入要删除的数"<<endl;
}
system("pause");
return 0;
}
#include "stdio.h"
#include "malloc.h"
struct Node
{
int data;
struct Node* next;
};
struct Node* creat()//创建一个单链表
{
struct Node *head,*p,*rear;//定义指针变量
head=(struct Node *)malloc(sizeof(struct Node));//申请 struct Node 类型字节长的存储空间
rear=head;
int data;
printf("输入一组数据,输入-1结束:");
scanf("%d",&data);
while(data!=-1)
{
p=(struct Node *)malloc(sizeof(struct Node));//申请 struct Node 类型字节长的存储空间
p->data=data;//将输入的值取出一个值并存储在结点 p 的数据域中
rear->next=p;//将结点 p 的首地址存放在 p 的前驱结点的指针域中
rear=p;//rear指针后移到下一个结点首地址处
scanf("%d",&data);//继续从输入的值中取出另一个值
}
rear->next=NULL; //指针 rear 移至最后一个结点处,将此结点的指针域 制空(NULL )
return head;
}
void print(Node* head)//输出链表函数
{
struct Node *p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void find(Node* head)//查找函数
{
int ins;
printf("输入查找数据:");
scanf("%d",&ins);
struct Node *p=head->next;
struct Node *s=head;
while(p!=NULL)
{
if(p->data==ins)
{
printf("YES\n");
s->next=p->next;
return;
}
else
{
s=p;
p=p->next;
}
}
printf("NO\n");
}
void main()
{
Node* head;
head = creat();
print(head);
find(head);
print(head);
}