#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node *link;
typedef struct node{
int element;
link next;
}Node;
link NewNode()
{
return (link)malloc(sizeof (Node));
}
typedef struct llist *List;
typedef struct llist {
link first,curr,last;
}Llist;
List ListInit()
{
List L=(List)malloc(sizeof*L);
L->first=0;
return L;
}
link creat(int n)
{
link head,mid,end;
head=(link)malloc(sizeof(Node));
end=head;
for(int i=0;i<n;i++)
{
mid=(link)malloc(sizeof(Node));
cin>>end->element;
end->next=mid;
end=mid;
}
end->next=NULL;
return head;
}
int ListEmpty(List L)
{
return L->first==0;
}
int ListLength(List L)
{
int len=-1;
link p=L->first;
while(p)
{
len++;
p=p->next;
}
return len;
}
int ListRetrieve(int k,List L)
{
if(k<1)return 0;
link p=L->first;
int i=1;
while(p&&i<k)
{
p=p->next;
i++;
}
return p->element;
}
int Listlocate(int x,List L)
{
int i=1;
link p=L->first;
while(p&&p->element!=x)
{
p=p->next;
i++;
}
return p?i:0;
}
void ListInsert(int k,int x,List L)//在L的第k处后面插入x
{
if(k<0)return ;
link p=L->first;
for(int i=1;i<k&&p;i++)p=p->next;
link y=NewNode();
y->element=x;
if(k){
y->next=p->next;p->next=y;
}
else{
y->next=L->first;
L->first=y;
}
}
int ListDelete(int k,List L)
{
if(k<0||!L->first)return 0;
link p=L->first;
if(k==1){L->first=p->next;
}else
{
link q=L->first;
for(int i=1;i<k-1&&q;i++)q=q->next;
p=q->next;
q->next=p->next;
}
int x=p->element;
free(p);
return x;
}
void PrintList(List L)
{
for(link p=L->first;p->next;p=p->next)
{
cout<<p->element<<" ";
}
}
int main()
{
int n;
List a_ptr=ListInit();
cout<<"输入链表的长度:";
cin>>n;
cout<<"输入链表的元素:";
a_ptr->first=creat(n);
cout<<"链表是为空吗?:"<<ListEmpty(a_ptr)<<endl;
cout<<"链表长:"<<ListLength(a_ptr)<<endl;
cout<<"链表第四个数:"<<ListRetrieve(4,a_ptr)<<endl;
cout<<"链表4的位置:"<<Listlocate(4,a_ptr)<<endl;
PrintList(a_ptr);cout<<endl;
ListInsert(1,100,a_ptr);
PrintList(a_ptr);cout<<endl;
cout<<"删除的第二个元素是:"<<ListDelete(2,a_ptr)<<endl;
PrintList(a_ptr);cout<<endl;
return 0;
}
//输入链表的长度:9
//输入链表的元素:1 2 3 4 5 6 7 8 9
//链表是为空吗?:0
//链表长:9
//链表第四个数:4
//链表4的位置:4
//1 2 3 4 5 6 7 8 9
//1 100 2 3 4 5 6 7 8 9
//删除的第二个元素是:100
//1 2 3 4 5 6 7 8 9
//
//--------------------------------
//Process exited after 4.235 seconds with return value 0
//请按任意键继续. . .
单链表实现C++
最新推荐文章于 2024-05-16 21:12:43 发布