先是代码:
AC代码:
shuanglist.cpp
#include"shuanglist.h"
#include<bits/stdc++.h>
using namespace std;
//void creat(dlinknode *head,int num)///这个是尾插法建立起来的双链表
//{
// int i;
// dlinknode *p,*r;
// r=head;
// for(i=0;i<num;i++)
// {
// p=(struct node *)malloc(sizeof(struct node));
// cin>>p->data;
// r->next=p;
// p->prior=r;
// p->next=NULL;
// r=p;
// }
//}
void creat(dlinknode *head,int num)///这个是头插法
{
int i;
dlinknode *p,*q;
q=(struct node *)malloc(sizeof(struct node));
cin>>q->data;
head->next=q;
q->prior=head;
q->next=NULL;
for(i=0;i<num-1;i++)
{
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
head->next=p;
p->next=q;
q=p;
p->prior=head;
}
}
void display(dlinknode *p)///输出
{
p=p->next;
while(p->next!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<p->data<<endl;
// while(p->prior!=NULL)
// {
// cout<<p->data<<' ';
// p=p->prior;
// }
// cout<<endl;
}
void charu(dlinknode *p,int k,int t)///在双链表的第k个节点插入元素t
{
int i,h=1;
dlinknode *r,*q;
if(k<0)
return;
while(h<k&&p!=NULL)
{
h++;
p=p->next;
}
if(p==NULL)
return;
q=p->next;
r=(struct node *)malloc(sizeof(struct node));
r->data=t;
r->prior=p;
r->next=p->next;
q->prior=r;
p->next=r;
}
void shanchu(dlinknode *p,int g)///删除双链表的第g个节点
{
int i,h=1;
dlinknode *r,*q;
if(g<0)
return;
while(h<g-1&&p!=NULL)
{
h++;
p=p->next;
}
if(p==NULL)
return;
r=p->next->next;
p->next=r;
r->prior=p;
}
int shuangempty(dlinknode *p)///判断是否为空
{
return (p->next==NULL);
}
int chang(dlinknode *p)///求链表的长
{
int length=0;
p=p->next;
while(p!=NULL)
{
p=p->next;
length++;
}
return length;
}
int getelem(dlinknode *p,int g)///获取链表第g个节点的值
{
int i,s=0;
if(g<0)
return -1;
while(p!=NULL&&s<g)
{
s++;
p=p->next;
}
if(p==NULL)
return -1;
return p->data;
}
int cha(dlinknode *p,int x)///查找链表中是否存在元素x
{
p=p->next;
while(p!=NULL)
{
if(p->data!=x)
{
p=p->next;
}
else
return 1;
}
}
shuanglist.h
#ifndef SHUANGLIST_H_INCLUDED
#define SHUANGLIST_H_INCLUDED
typedef struct node
{
int data;
node *prior;
node *next;
}dlinknode;
void creat(dlinknode *head,int num);
void display(dlinknode *p);
void charu(dlinknode *p,int k,int t);
void shanchu(dlinknode *p,int g);
int shuangempty(dlinknode *p);
int chang(dlinknode *p);
int getelem(dlinknode *p,int g);
int cha(dlinknode *p,int x);
#endif // SHUANGLIST_H_INCLUDED
main.cpp
#include<bits/stdc++.h>
#include"shuanglist.h"
using namespace std;
int main()
{
dlinknode *head;
head=(struct node *)malloc(sizeof(struct node));
head->prior=NULL;
int num,a,b,c,d;
cin>>num;
creat(head,num);
display(head);
a=chang(head);
b=shuangempty(head);
c=getelem(head,6);
d=cha(head,9);
cout<<a<<' '<<b<<' '<<c<<' '<<d<<endl;
charu(head,8,100);
display(head);
shanchu(head,1);
display(head);
return 0;
}
因为有两种建表的方式,一种是头插法,另一种是尾插法;因为尾插法一直有指针跟在尾部,所以我又将表中的元素从尾到头输出了一遍;而头插就不行了,除非单独再设置新的指针,所以在分别使用两种建表方法时的输出有些不同!
截图:
还是很有意思的呀!
知识点总结:
都是类似的,要能触类旁通,举一反三!
心得总结:
多练多写不要懈怠,争取在规定时间内完成任务!