#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
//链表的建立,创建有n个结点的链表
node *create(int n)
{
node *head=NULL;
node *p=NULL;
head=new node();
p=head;
cin>>p->data;
node *q;
while(--n)
{
q=new node();
cin>>q->data;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
//打印结点
void print(node *head)
{
node *p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//插入结点
//在指定位置weizhi上插入结点值为n的结点
//这里注意返回值不能写成void因为当weizhi为0的时候,head的值变动了,如果不返回head虽然那么原函数中的head还在原来的位置
node* insert(node *head,int weizhi,int n)
{
node *p=NULL;
if(weizhi<0)
{
return 0;
}
if(weizhi==0)
{
p=new node();
p->data=n;
p->next=head;
head=p;
}
if(weizhi>0)
{
p=head;
int num=weizhi;
while(--num)
{
p=p->next;
}
node *t=p->next;
node *q=new node();
q->data=n;
p->next=q;
q->next=t;
}
return head;
}
//删除第一个值为n的结点
node *delete_node(node *head,int n)
{
if (head==NULL)
{
return NULL;
}
else if(head->data==n)
{
node *p=head;
head=head->next;
delete p;
return head;
}
else
{
node *p,*q;
p=head;
q=p->next;
while(q!=NULL && q->data!=n)
{
p=p->next;
q=q->next;
}
if(q==NULL)
{
return head;
}
else
{
p->next=q->next;
delete q;
return head;
}
}
}
//链表的逆转
node *reverse(node *head)
{
node *p=NULL;//指向要逆转指针的前一个结点
node *r=head;//指向要逆转的结点
node *q=NULL;//指向要逆转结点的后一个结点
while(r!=NULL)
{
q=r->next;
r->next=p;
p=r;
r=q;
}
head=p; //注意全都逆转之后,结点r已经为NULL,结点p才是最后一个有数据的结点
return head;
}
int main()
{
node *head=create(5);
print(head);
head=insert(head,2,100);
print(head);
head=insert(head,0,1000);
print(head);
head=delete_node(head,3);
print(head);
head=delete_node(head,5);
print(head);
head=delete_node(head,1000);
print(head);
head=reverse(head);
print(head);
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有