#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Lianbiao{
typedef int datatype; //给int起个别名,主要为了程序扩展,之后可以将int换成其他数据类型
public:typedef struct Node{
datatype data;
struct Node *next;
}linknode,*linklist;
public :linklist createList(){ //初始化链表
linklist head;
if((head=(linklist)malloc(sizeof(linknode)))==NULL){
cout<<"创建链表失败"<<endl;
return head;
}
head->data=0;
head->next=NULL;
return head;
}
//获取链表尾结点
public :linklist getRear(linklist head){
if(head==NULL){
cout<<"链表不存在!"<<endl;
return head;
}
while(head->next!=NULL){
head=head->next;
}
return head;
}
//从链表头部插入
public :int headInsert(linklist head,datatype data){
if(head==NULL){
return -1;
}
linklist p;
if((p=(linklist)malloc(sizeof(linknode)))==NULL){
return -1;
}
p->data=data;
p->next=head->next;
head->next=p;
return 0;
}
//从链表尾部插入
public :int rearInsert(linklist head,datatype data){
linklist rear=getRear(head);
linklist p;
if((p=(linklist)malloc(sizeof(linknode)))==NULL){
return -1;
}
p->data=data;
p->next=NULL;
rear->next=p;
rear=p;
return 0;
}
//从链表头部删除
public :int deleteHead(linklist head){
if(head==NULL||head->next==NULL){
cout<<"链表不存在或为空!"<<endl;
return -1;
}
linklist p;
p=head->next;
head->next=p->next;
free(p);
return 0;
}
//从链表尾部删除
public :int deleteRear(linklist head){
int i;
if(head==NULL||head->next==NULL){
cout<<"链表不存在或为空!"<<endl;
return -1;
}
int len=getLength(head);
for(i=0;i<len-1;i++){
head=head->next;
}
linklist p=head->next;
head->next=NULL;
free(p);
return 0;
}
//修改链表,将链表第x个值改为data
public:int updateList(linklist head,int x,datatype data){
if(head==NULL||head->next==NULL){
cout<<"链表不存在或为空!"<<endl;
return -1;
}
if(x>getLength(head)){
cout<<"修改失败因为"<<x<<"超出了链表长度!"<<endl;
return -1;
}
int i;
for(i=0;i<x;i++){
head=head->next;
}
head->data=data;
return 0;
}
//查询链表第x个值并返回
public:datatype selectList(linklist head,int x){
if(head==NULL||head->next==NULL){
cout<<"链表不存在或为空!"<<endl;
return -1;
}
if(x>getLength(head)){
cout<<"查询失败因为"<<x<<"超出了链表长度!"<<endl;
return -1;
}
int i;
for(i=0;i<x;i++){
head=head->next;
}
return head->data;
}
//打印链表
public :int printList(linklist head){
if(head==NULL||head->next==NULL){
cout<<"链表不存在或为空!"<<endl;
return -1;
}
while(head->next!=NULL){
head=head->next;
cout<<head->data<<" ";
}
cout<<endl;
return 0;
}
//获取链表长度
public :int getLength(linklist head){
int count=0;
if(head==NULL){
cout<<"链表不存在!"<<endl;
return -1;
}
while(head->next!=NULL){
head=head->next;
count++;
}
return count;
}
//测试链表
void testLianbiao(){
int i;
linklist list=createList();
for(i=1;i<=5;i++){
headInsert(list,i*10);
}
printList(list);
for(i=1;i<=3;i++){
rearInsert(list,i*5);
}
printList(list);
cout<<"尾部结点:"<<getRear(list)->data<<endl;
cout<<"链表长度:"<<getLength(list)<<endl;
deleteHead(list);
printList(list);
deleteRear(list);
printList(list);
updateList(list,20,250);
printList(list);
cout<<selectList(list,1)<<endl;
cout<<selectList(list,2)<<endl;
cout<<selectList(list,10)<<endl;
}
};
int main(){
Lianbiao b;
b.testLianbiao();
system("pause");
return 0;
}