【数据结构】单链表

参考 王道

#include<iostream>
#include<cstdio>
#include<malloc.h>
using namespace std;

typedef struct LNode{
	int data;
	struct LNode *next;
}LNode,*LinkList;

LinkList List_HeadInsert(LinkList &L){//逆向建立单链表 
	LNode *s;
	int x;
	L =(LNode*)malloc(sizeof(LNode));//创建头节点 
	L->next=NULL;//初始为空链表 
	scanf("%d",&x);//输入结点的值 
	while(x != 9999){//输入9999表示结束 
		s=(LNode*)malloc(sizeof(LNode));//创建新节点 
		s->data=x;
		s->next=L->next; //
		L->next=s;//将新节点插入表中,L为头指针 
		scanf("%d",&x); 
	} 
	return L;
} 

LinkList List_TailInsert(LinkList &L){//逆向建立单链表 
	int x;//设元素类型为整型 
	L=(LNode *)malloc(sizeof(LNode)); 
	LNode *s;
	LNode *r=L;//r为表尾指针 
	scanf("%d",&x);//输入结点的值 
	while(x!=9999){//输入9999表示结束 
		s=(LNode*)malloc(sizeof(LNode));
		s->data=x;
		r->next=s;
		r=s; //r指向新的表尾结点 
	    scanf("%d",&x);
	} 
	r->next=NULL;//尾结点指针置空 
	return L;
} 

//按序号查找节点值 
LinkList GetElem(LinkList L,int i){
	int j=1;//计数,初始值为1 
	LNode *p=L->next;//头节点指针赋值给p 
	if(i==0) 
		return L;//若i=0,则返回头结点 
	if(i<1)  
		return NULL;//若i无效,则返回NULL 
	while(p&&j<i){//从第1个结点开始找,查找第i个结点 
		p=p->next;
		j++;
	}
	return p;//返回第i个结点的指针,若i大于表长则返回NULL 
	 
} 

int PrintList(LinkList L){
	LNode *p=L->next;
	while(p->next!=NULL){
		 cout<<p->data<<"->"; 
		 p=p->next;
	}   
	cout<<p->data;
	cout<<endl;
	return 0;
} 

int LocateElem(LinkList L,int e){
	int sum = 1; 
	LNode *p = L->next;
	while(p!=NULL&&p->data!=e){
		p=p->next;
		sum++;
	}
	if(p==NULL)
		return -1;//-1代表不在表中 
	return sum;	
}

void DeleteNode(LinkList &L,int i){
	LNode *p=GetElem(L,i-1);
	LNode *s=p->next;
	p->next=s->next;
	free(s);
} 

void InsertNode(LinkList &L,int i,int e){
	LNode *s=(LNode*)malloc(sizeof(LNode));
	s->data=e; 
	LNode *p=GetElem(L,i-1);
	s->next=p->next;
	p->next=s; 
}

int GetLen(LinkList L){
	LNode *p = L->next;
	int sum =1;
	while(p->next!=NULL){
		p = p->next;
		sum++;
	}
	return sum;
}

int main(){
	cout<<"建立链表 输入9999停止"<<endl;
	LinkList L;
	List_HeadInsert(L);
	PrintList(L);
	int i;
	cout<<"请输入要查找的位置:"<<endl;
	cin>>i; 
	LNode *s =  GetElem(L,i);
	cout<<"表中第"<<i<<"是"<<s->data<<endl;
	int j;
	cout<<"请输入要查找的值:"<<endl;
	cin>>j; 
	cout<<"表中"<<j<<"位置是"<<LocateElem(L,j)<<endl;
	cout<<"请输入要删除的位置:"<<endl;
	int k;
	cin>>k; 
	DeleteNode(L,k);
	PrintList(L);
	cout<<"请输入要插入的位置:"<<endl;
	int l1;
	cin>>l1; 
	cout<<"请输入要插入的值:"<<endl;
	int l2;
	cin>>l2; 
	InsertNode(L,l1,l2);
	PrintList(L);
	cout<<"表长为:"<<GetLen(L)<<endl;
	return 0;
} 

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值