#include<iostream>
using namespace std;
typedef struct node{
int element;
node *next;
}list;
void Init(list *header){//初始化链表
int n; cin >> n;
for(int i=0; i<n; ++i){
list *temp = (list*)malloc(sizeof(list));
cin >> temp->element;
temp->next = NULL;
list *t = header;
while(t->next!=NULL){
t = t->next;
}
t->next = temp;
}
return ;
}
void Print(list *header){
list *t = header->next;
while(t!=NULL){
cout << t->element << " ";
t = t->next;
}
cout << endl;
return ;
}
void Insert(list *header){ //下标从零开始,先前插入
int n; cin >> n;
list *t = header;
for(int i=0; i<n; ++i){
if(t->next==NULL){
cout << "Out of space." << endl;
return ;
}
t = t->next;
}
list *temp = (list*)malloc(sizeof(list));
cin >> temp->element;
temp->next = t->next;
t->next = temp;
return ;
}
void Delet(list *header){ //下标从零开始
int n; cin >> n;
list *t = header;
for(int i=0; i<n; ++i){
if(t->next==NULL){
cout << "Out of space." << endl;
return ;
}
t = t->next;
}
if(t->next!=NULL)
t->next = t->next->next;
else
t->next = NULL;
return ;
}
int main(){
list *header = (list*)malloc(sizeof(list));
//node *header = (node*)malloc(sizeof(node));
//在C++中,结构体声明时可省略struct关键字
//第一个node代表(struct node)声明结构体的类型
//第二个代表强转malloc的返回值(malloc)的返回值为void
//第三个为求出node结构体的大小
header->next = NULL;
Init(header);
Print(header);
Insert(header);
Print(header);
Delet(header);
Print(header);
return 0;
}
链表
最新推荐文章于 2024-06-14 09:15:00 发布