#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
int length;
LNode * r;
void InitList(LinkList &L);
bool tailInsert(LinkList &L, int value);
void PrintList(LinkList L);
LNode *GetElem(LinkList L, int loc);
LNode *LocateElem(LinkList L, int e);
bool insert(LinkList &L, int value, int loc);
bool delNode(LinkList &L, int loc);
int main(){
LNode *L;
InitList(L);
int opt = 0;
while(opt != 7){
int value = -1;
int loc = -1;
printf("请选择你要执行的操作:\n1.尾插\n2.遍历\n3.按位获取节点\n4.按值获取结点\n5.按位插入结点\n6.按位删除结点\n7.退出\n");
cin >> opt;
LNode *n;
switch(opt){
case 1:
cin >> value;
tailInsert(L,value);
break;
case 2:
PrintList(L);
break;
case 3:
cin >> loc;
n = GetElem(L,loc);
cout << "获取到的值为:" << n->data << endl;
break;
case 4:
cin >> value;
n = LocateElem(L,value);
if(n != NULL){
cout << "获取到的值为:" << n->data << endl;
}
break;
case 5:
cin >> value >> loc;
insert(L,value,loc);
break;
case 6:
cin >> loc;
delNode(L,loc);
break;
}
}
cout << "退出成功";
return 0;
}
void InitList(LinkList &L){
L = (LNode*) malloc(sizeof (LNode));
L->next = NULL;
r = L;
length = 0;
}
bool tailInsert(LinkList &L, int value){
LNode *v;
v = (LNode*) malloc(sizeof (LNode));
if(v == NULL){
cout << "插入节点失败"<< endl;
return false;
}
r->next = v;
v->data = value;
r = v;
r->next = NULL;
PrintList(L);
length ++;
return true;
}
LNode *GetElem(LinkList L, int loc){
while(loc --){
L = L->next;
}
return L;
}
bool insert(LinkList &L, int value, int loc){
LNode *v = (LNode*)malloc(sizeof(LNode));
if(loc > length + 1){
cout << "传入下标有误" << endl;
return false;
}
LNode *t = GetElem(L,loc-1);
v->next = t->next;
t->next = v;
v->data = value;
cout << "插入成功"<<endl;
length ++;
PrintList(L);
return true;
}
bool delNode(LinkList &L, int loc){
if(loc > length){
cout << "该下标不存在"<< endl;
return false;
}
LNode *n = GetElem(L,loc-1);
LNode *q = n->next;
n->next = q->next;
free(q);
cout << "删除成功" << endl;
PrintList(L);
}
LNode *LocateElem(LinkList L, int e){
while(L != NULL){
if(L->data == e){
return L;
}
L = L->next;
}
cout<< "没有找到该值" << endl;
return NULL;
}
void PrintList(LinkList L){
cout << "遍历的结果为:" <<endl;
if(L->next != NULL){
L = L->next;
}
while(L != NULL){
cout << L->data << " ";
L = L->next;
}
cout << endl;
}
|