虽然单链表的操作因其存储结构而受限制,但这并不影响它可以有很多的有趣操作!以下列出三个;分别为单链表的逆置、两个单链表的连接和判断单链表是否递增。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
node *next;
}danlist;
danlist *head,*head1;
struct node * creat0(int num)///尾插法
{
int i;
danlist *p,*r,*tou;
tou=(struct node *)malloc(sizeof(struct node));
r=tou;
for(i=0;i<num;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->next=NULL;
cin>>p->data;
r->next=p;
r=p;
}
return tou;
}
//struct node * creat1(int num)///头插法
//{
// danlist *p;
// int i;
// head1=(struct node *)malloc(sizeof(struct node));
// head1->next=NULL;///不要忘了这个
// for(i=0;i<num;i++)
// {
// p=(struct node *)malloc(sizeof(struct node));
// cin>>p->data;
// p->next=head1->next;
// head1->next=p;
// }
// return head1;
//}
void display(danlist *p)
{
p=p->next;
while(p->next!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<p->data<<endl;
}
void deslist(danlist *p)
{
danlist *r;
while(p->next!=NULL)
{
r=p->next;
free(p);
p=r;
}
free(p);
cout<<"单链表已经被销毁"<<endl;
}
void link(danlist *head,danlist *head1)///在保证两个链表都不是空表的情况下!
{
while(head->next!=NULL)
{
head=head->next;
}
head->next=head1->next;///问题就在这里;真是画蛇添足呀!
}
int length(danlist *p)
{
int chang=0;
while(p->next!=NULL)
{
p=p->next;
chang++;
}
return chang;
}
void nizhi(danlist *p,int num)///这个逆置操作是受单链表的头插法的启示而写出来的!
{
int i;
danlist *r,*q;
r=p->next;
q=r->next;
p->next=NULL;
for(i=0;i<num-1;i++)
{
r->next=p->next;
p->next=r;
r=q;
q=r->next;
}
r->next=p->next;
p->next=r;
}
void dizeng(danlist *p)
{
int te=1;
danlist *r;
p=p->next;
r=p->next;
while(p->next!=NULL)
{
if(r->data>p->data)
{
p=r;
r=p->next;
}
else
{
te=0;
break;
}
}
if(te==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
int main()
{
int i;
head=creat0(5);
display(head);
head1=creat0(5);
display(head1);
dizeng(head1);
link(head,head1);
display(head);
nizhi(head,10);///先将两个长度为5的单链表连接起来,然后就地逆置!
display(head);
dizeng(head);
return 0;
}
运行结果截图如上!
知识点总结:
知识还是需要活学活用的;单链表的逆置就是受单链表的头插法的启示而修改来的,感觉真的是很有收获呀!
心得体会:
坚持每天都好好学习!