数据结构链表的增删查改(带头结点)

#include<iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
typedef struct LNode{
	int data;
	struct LNode *next;
}LNode,*LinkList;
LinkList InitList(LinkList &L)
{
	// It have the head list and the head node is null,so we can use it without restrict
	L=new LNode; 
	L->next=NULL;
	return L;
}
//LinkList InitList(LinkList &L)
//{
//	// It haven't head list and the head node is null,so we can use it without restrict
//	L=new LNode; 
//	L->data=1;
//	L->next=NULL;
//	return L;
//}
LinkList ListTailInsert(LinkList &L,int x){
	LNode *s1 = new LNode;
	LinkList s2=L;
	while(s2->next)
	{
		s2=s2->next;
	}
	s1->data = x;
	s1->next=s2->next;
	s2->next=s1;
	return L;
}
LinkList ListHeadInsert(LinkList &L,int x)
{
	LNode *s1 = new LNode;
	s1->data=x;
	s1->next=L->next;
	L->next=s1;
	return L;
}
LNode *GetElem(LinkList L,int x)
{
	int j=1;
	LNode *p =L->next;
	if(x==0)
		return p;
	if(x<1)
		return NULL;
	while(p&&j<x)
	{
		p=p->next;
		j++;
	}
	return(p);
}
LNode* LocateElem(LinkList L,int e){
	LNode *p = L;
	while(p)
	{
		if(p->data==e)
		{
			return p;
		}
		p=p->next;
	}
	return NULL;
}
LinkList Find_Tail_Insert(LinkList &L,LNode *node,int x)
{
	LNode *p;
	//p is the LNode of i-1 
	p=GetElem(L,x-1);
	node->next=p->next;
	p->next=node;
	// p is HeadInsert that is reverse i-1 and i
//	int temp=p->data;
//	p->data=node->data;
//	node->data=temp;
	return L;	
}
LinkList ListDelete(LinkList &L,int x)
{
	LNode *p,*q;
	p=GetElem(L,x-1);
	q=p->next;
	p->next=q->next;
	//free the memory
	free(q);
	return L;
}
int Length(LinkList L)
{
	int x=0;
	LinkList p=L->next;
	while(p)
	{
		x++;
		p=p->next;
	}
	return x;
}
void PrintList(LinkList L){
	LinkList s=L->next;
	while(s)
	{
		if(s->next==NULL)
		printf("%d",s->data);
		else
		printf("%d\n",s->data);
		s=s->next;
	}
	return ;
}
int main()
{
	int x;
	LNode *y = new LNode;
	y->data=999;
	y->next=NULL;
	LinkList L;
	L=InitList(L);
	L=ListHeadInsert(L,1);
	L=ListHeadInsert(L,2);
	L=ListHeadInsert(L,3);
	L=ListHeadInsert(L,4);
	
//	cout<<Length(L); output length of list
	
//	ListDelete(L,2);//delete node in the List
	
//	Find_Tail_Insert(L,y,3); // find out the site and interposition 
//	
//	y=LocateElem(L,2); //chase down node in the list
//	cout<<y->data;

//	cout<<GetElem(L,2);

//	L=ListTailInsert(L,1);
//	L=ListTailInsert(L,2);
//	L=ListTailInsert(L,3); 
//	L=ListTailInsert(L,4);

	PrintList(L);

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值