pta链表
程序员文章站
2024-03-23 14:50:40
...
pta 习题题目十一
代码有点长 可能和网上搜的有点出入
7-1
#include<bits/stdc++.h>
using namespace std;
typedef struct NODE{
int data;
struct NODE *next;
}*linke;
int m=sizeof(linke);
linke addend(){
linke head,node,s;
head=(linke)malloc(m);
//node=(linke)malloc(m);
int x;
cin>>x;
head->data=x;
node=head;
while(cin>>x&&x!=-1){
s=(linke)malloc(m);
s->data=x;
node->next=s;
node=s;
}
node->next=NULL;
return head;
}
void __put(linke head){
int flag=1;
while(head!=NULL){
if(flag)
cout<<head->data,flag=0;
else
cout<<"->"<<head->data;
//cout<<head->data<<" ";
head=head->next;
}
}
int main(){
linke head;
head=addend();
__put(head);
}
7-2
#include<bits/stdc++.h>
using namespace std;
typedef struct NODE
{
int data;
struct NODE *next;
}*linke;
linke head;
linke head1;
int m=sizeof(linke);
linke addend()
{
linke head1,node,s;
head1=(linke)malloc(m);
//node=(linke)malloc(m);
int x;
cin>>x;
head1->data=x;
node=head1;
while(cin>>x&&x!=-1)
{
s=(linke)malloc(m);
s->data=x;
node->next=s;
node=s;
}
node->next=NULL;
return head1;
}
linke __delete(linke head) //删除
{
int x;
cin>>x;
linke node,p,pre;
node=head;
while(node->data==x)
{
node=head->next;
head=node;
}
node=head;
while(node!=NULL)
{
//cout<<node->data<<" ";
if(node->data==x)
{
// pre=node->next;
p->next=node->next;
}
else
{
p=node;
//cout<<node->data<<endl;
}
node=node->next;
}
int flag=1;
while(head!=NULL)
{
if(flag)
cout<<head->data,flag=0;
else
cout<<"->"<<head->data;
//cout<<head->data<<" ";
head=head->next;
}
}
void __put(){
int flag=1;
while(head1!=NULL)
{
if(flag)
cout<<head1->data,flag=0;
else
cout<<"->"<<head1->data;
//cout<<head->data<<" ";
head1=head1->next;
}
cout<<endl;
}
int main()
{
head=addend();
head1=head;
__put();
head=__delete(head);
}
7-3
#include<bits/stdc++.h>
using namespace std;
typedef struct NODE
{
int data;
struct NODE *next;
}*linke;
linke head;
linke head1;
int m=sizeof(linke);
linke addend()
{
linke head1,node,s;
head1=(linke)malloc(m);
//node=(linke)malloc(m);
int x;
cin>>x;
if(x==-1){
head1=NULL;
return head1;
}
head1->data=x;
node=head1;
while(cin>>x&&x!=-1)
{
s=(linke)malloc(m);
s->data=x;
node->next=s;
node=s;
}
node->next=NULL;
return head1;
}
void __add() //增加
{
int x;
cin>>x;
if(head==NULL){
cout<<x;
return ;
}
linke p,node,p1;
node=head;
p=(linke)malloc(m);
p->data=x;
if(head->data>x)
{
head=p;
p->next=node;
//cout<<node->data<<" ";
}
else
{
while(node!=NULL)
{
if(node->data>x)
{
p->next=node;
p1->next=p;
break;
}
else
{
p1=node;
}
node=node->next;
}
}
int flag=1;
while(head!=NULL)
{
if(flag)
cout<<head->data,flag=0;
else
cout<<"->"<<head->data;
//cout<<head->data<<" ";
head=head->next;
}
if(node==NULL)
cout<<"->"<<x;
}
void __put()
{
int flag=1;
while(head1!=NULL)
{
if(flag)
cout<<head1->data,flag=0;
else
cout<<"->"<<head1->data;
//cout<<head->data<<" ";
head1=head1->next;
}
cout<<endl;
}
int main()
{
head=addend();
head1=head;
__put();
__add();
}
别让老师发现了 她发现了非得弄死我
上一篇: 双链表的定义及其基本操作
下一篇: Java面试宝典