线性表——单链表


一、源码

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; 
} 


总结

不供参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值