分享:双链表的简单操作
这是当时写的第一版本,插入函数修改指针部分,可以很大程度的精简,但是现在这样也有好处,易读。顺带说一个笑话:刚写这代码的时候,我给两个指针命名为left,rigth。然后left实际指向的是右边,而right实际指向的是左边。
当然郁闷了半天,结果一看,我他娘的画的图上面的指针就画反了。
程序代码:#include <stdio.h>
#include "Doubly_Linked_List.c"//这是为了测试偷懒,实际写代码别这么干
int main( void )
{
Node *RootP;
Node root;
int value;
root.Lprev = NULL;
root.Lnext = NULL;
root.Value = 0;
RootP = &root;
while( 1 == scanf("%d",&value) )
if ( InsertList( RootP, value ) )
root.Value++;
PrintList( RootP );
printf("%d\n",root.Value);
getchar();
while( 1 == scanf("%d",&value) )
if( Delete( RootP, value) )
root.Value--;
printf("\n");
PrintList( RootP );
printf("\n%d\n",root.Value);
DelList( RootP );
printf("\n");
PrintList( RootP );
printf("\n%d\n",root.Value);
return 0;
}
程序代码:typedef struct NODE {
int Value;
struct NODE *Lprev;
struct NODE *Lnext;
}Node;
enum{ False = 0, True };
int InsertList( Node *RootP, int value );//将元素插入有序的双链表,成功返回1,否则返回0
//不会插入重复的元素
void PrintList( Node *RootP );//打印双链表中的元素
int Delete( Node *RootP, int value );//删除双链表中的一个元素,成功返回1,否则返回0
void DelList( Node *RootP);//删除双链表
/*
* 未实现查找
*/
程序代码:#include "Doubly_Linked_List.h"
#include <stdlib.h>
#include <stdio.h>
int InsertList( Node *RootP, int value )
{
Node *This;
Node *Next;
Node *NewCell;
for( This = RootP; NULL != ( Next = This->Lprev ); This = Next )
{
if( value == Next->Value )
return False;
if( value < Next->Value )
break;
}
NewCell = ( Node * )malloc( sizeof( Node ) );
if( NULL == NewCell )
return False;
NewCell->Value = value;
if( NULL != Next )//如果Next不为NULL,则表示不在链表尾部
{
if( This != RootP )//如果This 不等于RootP,则表示不在链表头部
{
This->Lprev = NewCell;
Next->Lnext = NewCell;
NewCell->Lprev = Next;
NewCell->Lnext = This;
}
else
{//如果插入点在链表头部,那么RootP应该指向新的节点
RootP->Lprev = NewCell;
Next->Lnext = NewCell;
NewCell->Lprev = Next;
NewCell->Lnext = NULL;
}
}
else
{//如果在链表尾部
if( This != RootP )
{//如果在链表的尾部,哑节点的Lnext应该指向新的节点
This->Lprev = NewCell;
RootP->Lnext = NewCell;
NewCell->Lprev = NULL;
NewCell->Lnext = This;
}
else
{//如果是空表,哑节点应该指向新的节点
RootP->Lprev = NewCell;
RootP->Lnext = NewCell;
NewCell->Lprev = NULL;
NewCell->Lnext = NULL;
}
}
return True;
}
void PrintList( Node *RootP )
{
Node *This;
for( This = RootP->Lprev; NULL != This; This = This->Lprev )
printf("%d ",This->Value);
}
int Delete( Node *RootP, int value )//删除节点,需要修改两个指针,被删除的节点之前的节点的Lnext指针,以及被删除节点之后的Lperv指针。
{
Node *This;
Node *Next;
for( This = RootP; NULL != ( Next = This->Lprev ) && value != Next->Value;
This = Next )
;
if( NULL == Next )
return False;
if( NULL != Next->Lprev )
{
This->Lprev = Next->Lprev;
Next->Lprev->Lnext = This;
free( Next );
}
else
{
This->Lprev = NULL;
This->Lnext = RootP;
free( Next );
}
return True;
}
void DelList( Node *RootP )
{
Node *Temp;
Node *This;
This = RootP->Lprev;
while( NULL != ( Temp = This ) )
{
This = Temp->Lprev;
free( Temp );
}
RootP->Lprev = NULL;
RootP->Lnext = NULL;
}
[此贴子已经被作者于2017-3-23 21:10编辑过]








