//单链表的常用基本操作.cpp
#include<iostream>
using namespace std;
typedef struct Node{
char name[10];
int age,score;
struct Node* next;
}ListNode;
ListNode* Create_emptylist(void) //创建空链表,带头结点------------1
{
ListNode *temp=new ListNode;
temp->next=NULL;
return temp;
}
void Insert_list(ListNode *list,ListNode *pos,ListNode x) // 在pos后插入x-------------2
{
if(list==NULL) {
cout<<"list is empty!"<<endl;
return;
}
if(pos==NULL){
cout<<"Error position found!/n";
return;
}
ListNode *temp=new ListNode;
strcpy(temp->name,x.name);
temp->age=x.age;
temp->score=x.score;
temp->next=pos->next;
pos->next=temp;
}
void Delete_list(ListNode* list,ListNode* pos) //删除pos之后的结点-------------3
{
if(list==NULL){
cout<<"list is empty!"<<endl;
return;
}
if(pos==NULL){
cout<<"Error position found!/n";
return;
}
if(pos->next==NULL){
cout<<"No node after the postion!/n";
return;
}
ListNode *temp=pos->next;
pos->next=temp->next;
delete temp;
}
int Get_length(ListNode* list) //计算链表长度(元素个数)----------4
{
ListNode* tail=list;
int length=0;
while(tail->next!=NULL){
length++;
tail=tail->next;
}
return length;
}
ListNode* Get_position(ListNode* list,int order) //根据元素所在的位序,得到其位置值----5
{
if(! (order>=1 && order<=Get_length(list)) ){
cout<<"Error order found/n";
return NULL;
}
ListNode* t=list->next;
int num=1;
while(num<order){
num++;
t=t->next;
}
return t;
}
void browser(ListNode *list) //遍历链表(输出各元素值)-------6
{
ListNode *t=list->next;
cout<<"/nBrowsing the list:/n";
while(t!=NULL){
cout<<t->name<<","<<t->age<<","<<t->score<<endl;
t=t->next;
}
}
ListNode* Get_tail(ListNode* list) //得到链表的尾结点位置-----7
{
ListNode* tail=list;
while(tail->next!=NULL)
tail=tail->next;
return tail;
}
void Delete_list_order(ListNode* list,int order) //删除单链表中指定序号的元素-----8
{
ListNode* pos=Get_position(list,order); //该元素的位置
ListNode* pre=list;
while(pre->next!=pos) pre=pre->next; //求该元素的前驱结点的位置
Delete_list(list,pre);
}
void main(void)
{
ListNode *mylist;
mylist=Create_emptylist();
ListNode * tail=Get_tail(mylist);
for(int k=1;k<=3;k++){ //创建三个元素组成的链表
ListNode temp;
temp.next=NULL;
cout<<"/ninput the name:";
cin>>temp.name;
cout<<"input the age:";
cin>>temp.age;
cout<<"input the score:";
cin>>temp.score;
Insert_list(mylist,Get_tail(mylist),temp);
}
browser(mylist);
cout<<"the length of the list is "<<Get_length(mylist)<<endl;
Delete_list(mylist, Get_position(mylist,2) );
cout<<"after delete the node after No.2/n";
cout<<"the length of the list is "<<Get_length(mylist)<<endl;
browser(mylist);
Delete_list_order(mylist,1);
cout<<"after delete the first node:/n";
cout<<"the length of the list is "<<Get_length(mylist)<<endl;
browser(mylist);
}