您的位置:首页 > 理论基础 > 数据结构算法

数据结构链表——双链表

2015-07-24 22:58 423 查看
相对于单链表而言,双链表多了一个指向前方的指针,要注意的是头节点的前向指针始终为空。

与单链表一致的是,判断双链表是否为空,都是通过判断头节点的下一个节点是否为空来判断的。

双链表的操作与单链表的操作略有不同,主要是在插入操作和删除操作部分,有些额外的指针需要处理,另外特殊情况也需要考虑到,比如插入/删除之前链表为空。

代码如下:

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

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

List* initList( List **L )//make an empty List
{
	*L = ( List* )malloc( sizeof( struct List ) );
	(*L)->next = NULL;    //this is very important
	(*L)->pre = NULL;
	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 )
{
	List* tmp = ( List* )malloc( sizeof( struct List ) );
	if( tmp == NULL )
		std::cerr << "MEMORY OUT!" << std::endl;
	tmp->val = x;
	if( L->next == NULL )//the list is empty before insert the element x
	{
		tmp->next = L->next;
		tmp->pre = L;
		L->next = tmp;
	}
	else // the list is not empty
	{
		tmp->next = L->next;
		tmp->next->pre = tmp;
		tmp->pre = L;
		L->next = tmp;
	}
}

List* findPos( List* L, int x )//find element x in List L, return the priori list node
{
	List* position;
	List* tmp = L->next;
	if( L->next == NULL )
		return position;
	while( tmp != NULL && tmp->val != x )
		tmp = tmp->next;
	if( tmp->val == x)
		position = tmp;
	return position;
}

void deleteElem( List* L, int x )//delete element x in List
{
	List* tmp;
	List* position = findPos( L, x );
	if( position == NULL )
		std::cerr << "No Elem!" << std::endl;
	else
	{
		if( position->next == NULL )	//find the elem in the last node
		{
			position->pre->next = NULL;
			free( position );

		}
		else //find the element in the middle of List
		{
			position->next->pre = position->pre;
			position->pre->next = position->next;
			free( position );

		}
	}
}

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

void outputList( List* L )//output the 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)
{
	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, 9 );
	outputList( L );
	deleteList( L );
	std::cin.get();
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: