代码区——单链表

#include "stdafx.h"
#include<iostream>

using namespace std;


typedef struct Lnode                       //链表类型定义
{
	int data;
	struct Lnode* next;
}Lnode,*LinkList;


void CreateList_Head(LinkList& L, int N)     //头插法
{
	L = new Lnode;
	L->next = NULL;
	for (int i = N; i > 0; --i)
	{
		LinkList p = new Lnode;
		cin >> p->data;
		p->next = L->next;
		L->next = p;
	}

}

void CreateList_Rail(LinkList &L, int N)    //尾插法
{
	L = new Lnode;
	L->next = NULL;
	LinkList r = new Lnode;
	r = L;
	for (int i = 0; i < N; i++)
	{
		LinkList p = new Lnode;
		cin >> p->data;
		p->next = NULL;
		r->next = p;
		r = p;
	}
}

int GetElem(LinkList L, int i)         //取值(顺序存取)
{
	LinkList p = L->next;
	int j = 1;
	while (p&&j<i)
	{
		p = p->next;
		++j;
	}
	if (!p || j > i)
		return 0;
	return p->data;
}

Lnode* LocateElem_address(LinkList L, int e) //返回地址
{
	LinkList p = L->next;
	while (p&&p->data != e)
	{
		p = p->next;
	}
	return p;
}

int LocateElem_index(LinkList L, int e)     //返回位置 
{
	LinkList p = L->next;
	int j = 1;
	while (p&&p->data != e)
	{
		p = p->next;
		j++;
	}
	if (p)
		return j;
	else
		return 0;
}

void ListInsert(LinkList& L, int i, int e)   //在指定位置上插入元素
{
	LinkList p = L;
	int j = 0;
	while (p&&j < i - 1)
	{
		p = p->next;
		j++;
	}
	if (!p || j > i - 1)
		return;
	LinkList s = new Lnode;
	s->data = e;
	s->next = p->next;
	p->next = s;
	return;
}

void ListDelete(LinkList& L, int i, int& e)  //删除指定位置上的元素
{
	LinkList p = L;
	int j = 0;
	while (p&&j<i-1)
	{
		p = p->next;
		j++;
	}
	if (!p->next || j > i - 1)
		return;
	LinkList q = p->next;
	e = q->data;
	p->next = q->next;
	delete q;
	return;
}


int ListLength(LinkList L)                  //求链表的表长
{
	LinkList p = L->next;
	int i = 0;
	while (p)
	{
		i++;
		p = p->next;
	}
	return i;
}

void DestroyList(LinkList& L)                //销毁链表
{
	LinkList p;
	while (L)
	{
		p = L;
		L = L->next;
		delete p;
	}
	return;
}


void ClearList(LinkList& L)                   //清空链表
{
	LinkList p, q;
	p = L->next;
	while (p)
	{
		q = p->next;
		delete p;
		p = q;
	}
	L->next = NULL;
	return;
}

int main() 
{
	int N;
	cin >> N;
	LinkList L;
	//CreateList_Head(L, N);
	CreateList_Rail(L, N);
	int e=6;
//	e = GetElem(L, 4);
//	ListDelete(L, 4, e);
	ClearList(L);

	cout << ListLength(L)<<endl;

}



上一篇:双链表创建


下一篇:单链表的插入和删除