单链表的操作(C++)(实验2):
#include <iostream>
using namespace std;
//单链表单个结点的结构体
typedef struct LNode{
int data;
LNode *next;
}LNode, *LinkList;
//创建单链表(头插法)
void CreateList_H(LNode *L, int n){ //n为需要插入元素的个数
//步骤1:初始化头结点
L->data = 0;
L->next = NULL;
//步骤2:头插法创建单链表
for(int i=0; i<n; i++){
LNode *P = new LNode;
cin>>P->data;
P->next = L->next;
L->next = P;
}
}
//创建单链表(尾插法)
void CreateList_T(LNode *L, int n){
//步骤1:初始化头结点
L->data = 0;
L->next = NULL;
//步骤2:尾插法创建单链表
LNode *T = new LNode; //T始终指向末尾元素
T = L;
for(int i=0; i<n; i++){
LNode *p = new LNode;
cin>>p->data;
p->next = NULL;
T->next = p;
T = p;
}
}
//插入
void ListInsert(LNode *L, int loc, int elem){
LNode *p = new LNode;
p = L;
int temp = 0;
while(p){
if(temp!=loc-1){
p = p->next;
temp++;
}
else
break;
}
if(temp==loc-1 && p){ //注意:判断p不空才行,分析loc为末尾位置+2的情况
LNode *newnode = new LNode;
newnode->data = elem;
newnode->next = p->next;
p->next = newnode;
return ;
}
else{
cout<<"非法操作\n";
return ;
}
return ;
}
//删除
void ListDelete(LNode *L, int loc){
LNode *p = new LNode;
p = L;
int temp = 0;
while(p->next){
if(temp!=loc-1){
p = p->next;
temp++;
}
else
break;
}
if(temp==loc-1 && p->next){
p->next = p->next->next;
return ;
}
else{
cout<<"非法操作\n";
return ;
}
}
//查找某元素的位置
LNode *LocElem(LNode *L, int m){
LNode *p = new LNode;
p = L->next;
while(p){
if(p->data==m)
return p;
p = p->next;
}
cout<<"该元素不存在\n";
return NULL;
}
//查看某位置的元素
void GetElem(LNode *L, int loc){
LNode *p = new LNode;
p = L->next;
int temp = 1;
while(p){
if(temp!=loc){
p = p->next;
temp++;
}
else
break;
}
if(temp==loc && p){
cout<<p->data;
return ;
}
else{
cout<<"非法操作\n";
return ;
}
}
//打印单链表
void PrintList(LNode *L){
LNode *P = new LNode;
P = L->next;
while(P){
cout<<P->data<<endl;
P = P->next;
}
return ;
}
int main()
{
int n; LNode *L = new LNode; //创建头结点
cout<<"输入多少个数?\n";
cin>>n;
CreateList_T(L, n);
PrintList(L);
//插入
int loc, elem;
cout<<"输入插入位置和数据:";
cin>>loc>>elem;
ListInsert(L, loc, elem);
PrintList(L);
//删除
cout<<"输入删除的位置:";
cin>>loc;
ListDelete(L, loc);
PrintList(L);
//查找元素
cout<<"输入查找的元素:";
cin>>elem;
LNode *result = LocElem(L, elem);
cout<<"所在位置:"<<result<<endl;
//查看某位置的元素
cout<<"输入要查看的位置:";
cin>>loc;
GetElem(L, loc);
return 0;
}