<span style="font-size:18px;">#include<iostream>
using namespace std;
//节点结构体
typedef struct Node
{
int data;
Node *next;
}Node;
//创建单链表
Node *Creatlist()//返回指针值的函数
{
Node*head,*p,*q;
int i=0;
head=(Node*)malloc(sizeof(Node));
while(1)
{
int x;
cout<<"请输入链表的数据"<<endl;
cin>>x;
if(x==0)
break;
p=(Node*)malloc(sizeof(Node));
p->data=x;
if((++i)==1)
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
q->next=NULL;
return head;
}
//打印单链表
void print(Node* head)
{
Node *p;
if(head->next==NULL)
{
cout<<"链表为空"<<endl;
return ;
}
p=head->next;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
//测量链表的长度
int length(Node*head)
{
int len=0;
Node*p;
p=head->next;
while(p!=NULL)
{
len++;
p=p->next;
}
return len;
}
//取第i个节点数据
Node *GetNode(Node *h,int pos)
{
Node *p=h->next;
while(--pos)//注意此处是--pos而不是pos--
{
p=p->next;
}
return p;
}
//单链表的插入
Node *InsertNode(Node *h,int pos,int data)
{
Node *head=h;
Node *p=h;
while(pos--)
{
p=p->next;
}
Node *s=(Node *)malloc(sizeof(Node));
s->next=p->next;
p->next=s;
s->data=data;
return head;
}
//单链表的删除
//pos 节点删除位置
Node *DeleteNode(Node *h,int pos)
{
Node *head=h;
Node *p=h;
while(--pos)
{
p=p->next;
}
p->next=(p->next)->next;
return head;
}
//实现单链表的逆置
Node *ReverseNode(Node *h)
{
Node*p=h->next;
Node*q=p->next;
p->next=NULL;
Node*r;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
h->next=p;
return h;
}
//寻找链表的中间元素
Node *Search(Node *h)
{
Node*current=NULL;
Node*mid=NULL;
int i=0;
int j=0;
current=h->next;
mid=h->next;
while(current!=NULL)
{
if(i/2>j)
{
mid=mid->next;
j++;
}
i++;
current=current->next;
}
return mid;
}
//判断是否有环
bool IsCircle(Node*h)
{
Node*p1=h;
Node*P2=h;
do
{
p1=p1->next;
p2=p2->next->next;
}while(p2&&p2->next&&p2!=p1)
if(p1==p2)
{
return true;
}
else
{
return false;
}
}
int main()
{
cout<<"链表操作:"<<endl;
Node*head;
//创建数字链表
head=Creatlist();
//打印数字链表
print( head);
//判断链表是否存在环
Node*start=head->next->next->next;
start->next=head->next;
bool loop;
loop=IsCircle(head);
cout<<loop;
//寻找链表的中间元素
Node *mid;
mid= Search(head);
cout<<mid->data;
//求数字链表的长度
int L(0);
L=length(head);
cout<<L<<endl;
//求取某一节点的数据
Node *p;
int pos=3;
p=GetNode(head,pos);
cout<<p->data<<endl;
//在第i个节点后插入一个节点
int i;
cout<<"插入节点的位置:";
cin>>i;
int data;
cout<<"插入节点的数据:";
cin>>data;
head=InsertNode(head, i,data);
print( head);
//删除某一个节点
head=DeleteNode(head,3);
print(head);
//反转链表
head=ReverseNode(head);
print(head);
return 0;
}</span>
单链表的操作
最新推荐文章于 2021-02-01 02:25:42 发布