数据结构实验之链表一:顺序建立链表
#include <bits/stdc++.h>
using namespace std;
struct yyh
{
int data;
struct yyh* next;
}*head,*p,*tail;
int main()
{
int n;
scanf("%d",&n);
head=new struct yyh();
head->next=NULL;
tail=head;
for(int i=1; i<=n; i++)
{
p=new struct yyh();
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
p=head->next;
while(p!=NULL)
{
if(p->next!=NULL)
{
printf("%d ",p->data);
}
else
{
printf("%d\n",p->data);
}
p=p->next;
}
return 0;
}
数据结构实验之链表二:逆序建立链表
#include <bits/stdc++.h>
using namespace std;
struct yyh
{
int data;
struct yyh* next;
}*head,*p;
int main()
{
int n;
scanf("%d",&n);
head=new struct yyh();
head->next=NULL;
while(n--)
{
p=new struct yyh();
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
}
while(p!=NULL)
{
if(p->next!=NULL)
{
printf("%d ",p->data);
}
else
{
printf("%d\n",p->data);
}
p=p->next;
}
return 0;
}
数据结构实验之链表三:链表的逆置
#include <bits/stdc++.h>
using namespace std;
struct yyh
{
int data;
struct yyh* next;
}*head,*p;
int main()
{
int n;
head=new struct yyh();
head->next=NULL;
while(~scanf("%d",&n)&&n!=-1)
{
p=new struct yyh();
p->data=n;
p->next=head->next;
head->next=p;
}
while(p!=NULL)
{
if(p->next!=NULL)
{
printf("%d ",p->data);
}
else
{
printf("%d\n",p->data);
}
p=p->next;
}
return 0;
}
数据结构实验之链表四:有序链表的归并
这个题很有意思,尤其是mergeSort里的备注,关于地址和开空间的问题,是C/C++最有意思也挺有难度的地方,正是因为地址这种东西,C/C++才屹立不倒;
#include <bits/stdc++.h>
using namespace std;
struct yyh
{
int data;
struct yyh* next;
};
struct yyh* create(int w)
{
struct yyh* head=new struct yyh();
struct yyh* tail;
head->next=NULL;
tail=head;
while(w--)
{
struct yyh* p=new struct yyh();
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
struct yyh* mergeSort(struct yyh* head1,struct yyh* head2)
{
struct yyh* p,* q,* tail,* head;
head=new struct yyh();
//这里注意,我们要建立一个新的链表,他的头是head,但是这个head没有给它开辟空间
//所以我们必须先给head开辟一块新空间,mergeSort结束再把这个head的地址传给主函数里的head
//注意,这里的head和主函数里的head不是一个head,主函数里的head呢
//只是一个没有开辟它指向的struct yyh类型空间的指针。
//另外也不要给主函数里的head开辟空间,因为这里的head是我们新建出来的,他不能指向主函数里
//那个head指向的空间,依旧需要重新建立空间;
//当然,如果你非要用主函数里的那个head,可以看下面一个代码
//那个就是把主函数里的head传到这里来了;
p=head1->next;
q=head2->next;
head->next=NULL;
tail=head;
delete(head1);
delete(head2);
while(p!=NULL&&q!=NULL)
{
if(p->data<=q->data)
{
tail->next=p;
tail=p;
p=p->next;
tail->next=NULL;
}
else
{
tail->next=q;
tail=q