数据结构之链表

链表的实现以及链表中的常用操作

代码如下:

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

struct List{
	int val;
	List *next;
};

List* initList( List **L )//make an empty List
{
	*L = ( List* )malloc( sizeof( struct List ) );
	(*L)->next = NULL;    //this is very important
	return *L;
}

bool isEmpty( List* L)//test the list is an empty list or not
{
	return L->next == NULL;
}

void insert( List* L, int x )//insert an elem
{
	List* tmp = ( List* )malloc( sizeof( struct List ) );
	if( tmp == NULL )
		std::cerr << "MEMORY OUT!" << std::endl;
	tmp->val = x;
	tmp->next = L->next;
	L->next = tmp;
}
List* findPri( List* L, int x )//find element x in List L, return the previous list node
{
	List* position;
	List* tmp = L;
	if( L->next == NULL )
		return position;
	while( tmp->next != NULL && tmp->next->val != x )
		tmp = tmp->next;
	if( tmp->next->val == x)
		position = tmp;
	return position;
}

List* findPos( List* L, int x )//find element x in List L
{
	List* pos = findPri( L, x );
	if( pos != NULL )
		return pos->next;
	else 
		return NULL;
}

void deleteElem( List* L, int x ) //Delete elem x in List L,if not found, output error
{
	List* tmp;
	List* position = findPri( L, x );
	if( position == NULL )
		std::cerr << "No Elem!" << std::endl;
	else
	{
		tmp = position->next;
		position->next = tmp->next;
		free( tmp );
	}
}

void deleteList( List *L )//delete whole List 
{
	List *tmp;
	while( L->next != NULL )
	{
		tmp = L->next;
		L->next = L->next->next;
		free( tmp );
	}
}

void outputList( List* L )// output the whole List
{
	List* tmp = L;
	while( tmp->next != NULL )
	{
		std::cout << tmp->next->val << " ";
		tmp = tmp->next;

	}
	std::cout << std::endl;
}

int main( int _argc, char **__argv)//Main function
{
	int arrcnt = 10;
	int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	List* L;
	initList( &L );
	for( int i = 0; i < arrcnt; ++i )
		insert( L, arr[i] );

	outputList( L );

	//List* pos = findPri( L, 5);
	//std::cout << pos->val << std::endl;
	deleteElem( L, 5 );
	outputList( L );
	deleteList( L );
	std::cin.get();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值