王道ch1-单链表的定义,创建,按序号查找,按值查找,插入,删除,求表长

定义

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

创建,分为头插法和尾插法

//单链表头插法
LinkList headInsert(LinkList& L)
{
	int x; LNode* s;
	L = (LinkList)malloc(sizeof(LNode));
	L->next = NULL;
	cin >> x;
	while (x != 9999)
	{
		s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		s->next = L->next;
		L->next = s;
		cin >> x;
	}
	return L;
}
//单链表尾插法
LinkList tailInsert(LinkList& L)
{
	int x;
	L = (LinkList)malloc(sizeof(LNode));
	LNode* s, * r = L;
	cin >> x;
	while (x != 9999)
	{
		s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r = s;

		cin >> x;
	}
	r->next = NULL;
	return L;
}

按序号查找按值查找

//单链表按序号查找结点值
LNode* GetElem(LinkList& L,int i)
{
	LNode* p = L->next;
	int j = 1;
	if (i == 0)
		return L;
	if (i < 0)
		return NULL;
	while (p&&jnext; j++;
	}
	return p;
}

//单链表按值查找e
LNode* LocatedElem(LinkList& L, int x)
{
	LNode* p = L->next;
	while (p)
	{
		if (p->data == x)
			return p;
		p = p->next; 
	}
	return NULL;
}

插入

//单链表  在i位置插入新结点
LinkList H_Insert_x(LinkList& L, int i)
{
	int x;
	LNode*s,*p;
	p=GetElem(L,i-1);
	s = (LNode*)malloc(sizeof(LNode));
	cin >> x;
	s->data = x;
	s->next = p->next;
	p->next = s;
	return L;
}

int main()
{
	LinkList L;
	tailInsert(L);
	H_Insert_x(L, 2);
	LNode* p = L->next;
	while (p)
	{
		cout << p->data << " ";
		p = p->next;
	}
	return 0;
}

删除

//单链表  删除i位置结点
LinkList Delete(LinkList& L, int i)
{
	int x;
	LNode *p,*q;
	p = GetElem(L, i - 1);
	q=p->next ;
	x = q->data;
	p->next = q->next;
	free(q);
	return L;
}

求表长

//单链表  计算单链表长度
int count(LinkList& L)
{
	if (L->next == NULL)
		return 0;
	int count=1;
	LNode *p=L->next;
	while (p->next)//注意是p指向空,而不是p为空
	{
		p = p->next; count++;
	}
	return count;
}

 

你可能感兴趣的:(数据结构考研王道)