一、源码
1.创建、获取、插入、删除
代码如下(示例):
#include <iostream>
#include <cstdio>
#include <malloc.h>
using namespace std;
#define ok 1
#define error 0
typedef int status;
typedef struct linklist{
linklist *next;
int s;
} Lnode, *LList;
status Init (LList *L){
(*L) = (LList)malloc(sizeof(Lnode));
(*L)->next = NULL;
printf("单链创建ok\n");
return ok;
}
void create (LList L){
int n;
printf("cin the all sums :");
scanf(" %d",&n); //要创建的节点个数
LList p = L;
for(int i = 0;i < n;i ++){
LList lnew;
lnew = (LList)malloc(sizeof(Lnode));
int date;
scanf(" %d",&date); //输入date域
lnew->s = date;
lnew->next = NULL;
p->next = lnew;
p = lnew;
}
//printf("%d",p->s);
}
status Getelem(LList L){
if(L->next == NULL) return error;
LList p;
p = L->next;
//printf("%d",p->s);
printf("输入目标值:\n");
int point;
scanf("%d",&point);
int i = 1;
while (p && i < point) { //此处不可 i<=position,因为while成立时,内部会i++
p = p->next;
//printf("%d",p->s);
i++;
}
//if(!p || i > point); return error;
int e = p->s;
printf("%d",e);
}
status InSert(LList L){
if(L->next == NULL) return error;
int post;
printf("cin your wanna position :)\n");
scanf("%d", &post);
LList p;
p = L;
int j = 0;
while(j < post - 1){ //插入时找到此位置之前那个节点 即post-1的位置
j ++;
p = p->next;
}
//printf("%d",p->s);
//if(!p || j > post - 1) return error;
LList lnew;
lnew = (LList)malloc(sizeof(Lnode));
int elem;
printf("cin the inserted elem: ");
scanf("%d", &elem);
lnew->s = elem;
lnew->next = p->next;
p->next = lnew;
return ok;
}
status deleted(LList L){
if(L->next == NULL) return error;
int post;
printf("cin your wanna deleted position :)\n");
scanf("%d", &post);
LList p;
p = L;
int j = 0;
while(j < post - 1){ //插入时找到此位置之前那个节点 即post-1的位置
p = p->next;
j ++;
}
//if(!p || j > post - 1) return error;
LList s = new Lnode;
int elem;
LList pfree = p->next;
elem = pfree->s;
p->next = pfree->next; //此处可改写成 p->next = p->next->next;
free(pfree);
return ok;
}
int main(){
Lnode* L ;
Init(&L);
create (L);
int x;
while(1){
printf("************************线性表:**************************\n");
printf("菜单选择:1.获取值2.插入3.删除\n");
scanf("%d",&x);
switch(x){
case 1: int e;
Getelem(L); break;
case 2: InSert(L); break;
case 3: deleted(L); break;
//default: return error;
}
// case 3:
// case 4:
}
//create (L);
//int e;
//Getelem(L);
return 0;
}
总结
不供参考