您的位置:首页 > 编程语言 > C语言/C++

单链表的建立,测长度,打印,删除,插入,逆置c++代码实例及运行结果

2018-02-02 15:06 531 查看
c++代码

#include <iostream>

using namespace std;

typedef struct st
{
int data;
struct st *next;
}node;

//单链表的创建
node *create()
{
node *head,*p,*s;
int x,cycle;
head=(node*)malloc(sizeof(node));
p=head;
while(cycle)
{
cout<<"请依次输入单链表的元素"<<endl;
cin>>x;
if(x!=0)//输入0是结束输入
{
s=(node*)malloc(sizeof(node));
s->data=x;
p->next=s;//p在前,s在后
p=s;
}
else cycle=0;
}
head=head->next;
p->next=NULL;

return(head);
}

//测量单链表的长度
int length(node *head)
{
int n=0;
node *p;
p=head;
while(p!=NULL)
{
p=p->next;
n++;
}
return n;
}

//单链表的打印
void print(node *head)
{
node *p;
p=head;
if(head!=NULL)
{
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
}

//单链表删除节点
node *del(node *head,int num)
{
node *p1,*p2;
p1=head;
while(num!=p1->data&&p1->next!=NULL)//未遇到要删除的元素
{
p2=p1;
p1=p1->next;//p1在前,p2在后
}
if(num==p1->data)//遇到要删除的元素
{
if(p1==head)//如果删除的为头结点
{
head=p1->next;
free(p1);
}
else
p2->next=p1->next;//原来的p2->next指向p1,现在变为p1->next
}
else
cout<<"不能找到要删除的元素"<<endl;

return head;
}

//单链表的插入
node *insert(node *head,int num)
{
node *p0,*p1,*p2;
p1=head;
p0=(node*)malloc(sizeof(node));
p0->data=num;
while(p0->data>p1->data&&p1->next!=NULL)//插入条件p0->data<=p1->data
{
p2=p1;
p1=p1->next;
}
if(p0->data<=p1->data)
{
if(head==p1)//头插入
{
p0->next=p1;
head=p0;
}
else//中间插入
{
p2->next=p0;
p0->next=p1;
}
}
else//尾部插入
{
p1->next=p0;
p0->next=NULL;
}
return head;
}

//单链表的逆置
node *reverse(node *head)
{
node *p1,*p2,*p3;
if(head==NULL||head->next==NULL)//不需要逆置的情况
return head;

p1=head;
p2=p1->next;//p2当前节点,p1前一个节点,p3后一个节点
while(p2)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
head->next=NULL;
head=p1;

return head;
}

int main()
{
node *head;
int insert_num,del_num;
int len;
head=create();
len=length(head);
cout<<"单链表的长度为"<<len<<endl;
print(head);
4000

cout<<"请输入插入的元素x"<<endl;
cin>>insert_num;
head=insert(head,insert_num);
len=length(head);
cout<<"单链表的长度为"<<len<<endl;
print(head);

cout<<"请输入删除的元素x"<<endl;
cin>>del_num;
head=del(head,del_num);
len=length(head);
cout<<"单链表的长度为"<<len<<endl;
print(head);

cout<<"逆置后的单链表为"<<endl;
head=reverse(head);
len=length(head);
cout<<"单链表的长度为"<<len<<endl;
print(head);

return 0;
}


运行后结果为

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐