#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct node{
int data;
struct node*next;
}node;
node*tou(node*head,int num)//从头部插入num
{
node*p=NULL;
p=(node*)malloc(sizeof(node));
p->data=num;
p->next=head->next;
head->next=p;
return head;
}
node*wei(node*head,int num)//从尾部插入num
{
node*p=NULL;
node*l=NULL;
l=head;
while(l->next!=NULL)
l=l->next;
p=(node*)malloc(sizeof(node));
p->data=num;
p->next=NULL;
l->next=p;
return head;
}
node*insert(int i,node*head,int da)//在i位置插入da
{
node*p=head;
int j=1;
while(p&&j<i)
{
p=p->next;
++j;
}
if(!p||j>i) return 0;
node*s=(node*)malloc(sizeof(node));
s->data=da;
s->next=p->next;
p->next=s;
return head;
}
void del(node *head,int num)//删除值为num的节点
{
node *p=NULL; p=head;
node *pf=NULL;//记录p的前节点
while((p->next!=NULL)&&p->data!=num)
{
pf=p;
p=p->next;
}
if(p->next==NULL&&p->data!=num)
printf("不存在值为%d的节点",num);
else
{
pf->next=p->next;
}
}
int del1(node*head,int i) //删除i位置的节点
{
int da;
node*p=NULL;p=head;
node*q=NULL;
int j=1;
while((p->next!=NULL)&&j<i)
{
p=p->next;++j;
}
if((p->next==NULL)||j>i)
cout<<"链表不存在"<<i<<"位置的节点"<<endl;
else
{
da=p->next->data;
q=p->next;p->next=q->next;
} return da;
}
int search(node*head,int i)
{
int da;
node*p=NULL;p=head->next;//p指向链表的第一个节点
int j=1;
while(p!=NULL&&j<i)
{
p=p->next;++j;
}//直到i=j,p找到i位置,跳出循环
if(p==NULL||j>i)
cout<<"链表中此节点不存在"<<endl;
da=p->data;
return da;
}
void out(node*head)//输出链表
{
node*temp=head->next;//注意是=head->next;
while(temp)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main()
{
int sh1,sh2,x;node*p=NULL;char ch;int flag=0;
node*head = (node *)malloc(sizeof(node));
head->next=NULL;//建立一个链表头
p=head->next;
int i;
while(cin>>i)
{
//tou(head,i);
wei(head,i);
out(head);
cout<<endl;
}
insert(3,head,8);out(head);cout<<endl;
//del(head,5);out(head);cout<<endl;
//sh1=del1(head,6);out(head);cout<<endl;
//sh2=search(head,7);out(head);cout<<endl;cout<<sh2;cout<<endl;
system("pause");
return 0;
}
链表的基本操作(c链表实现)
最新推荐文章于 2022-10-29 15:47:30 发布