双向链表插入错误,我真的已经认真思考过来
DuList.c.rar
(217.5 KB)
运行时错误,插入不对
#include "ElemType.h"
#include "DuNode.h"
#include "stdlib.h"
#include "stdio.h"
DuLinkList Init(){
DuLinkList L = ( DuLinkList ) malloc ( sizeof ( DuNode ) ) ;
L -> data = 0 ;
L -> next = L -> prior = NULL ;
return L;
}
void Insert ( DuLinkList L , int i , ElemType e ) {
DuLinkList s , p = L->next ;
int k ;
if(i < 1 || i > GetLength( L )+1 )
{
printf( "插入数据位置错误\n" ) ; return ;
}
s = ( DuLinkList ) malloc ( sizeof ( DuNode ) ) ;
s -> data = e ;
for( k = 1 ; k < i ; k++)
{ //找到插入的位置的后一个节点
p = p -> next ;
}
s->prior = p ->prior ;
p->prior->next = s;
s->next = p;
p->prior = s;
}
int GetLength( DuLinkList L ){
int k = 0 ;
DuLinkList p = L ;
while ( p->next )
{
k ++ ;
}
return k ;
// return L -> data ;
}
void DeleteIndex ( DuLinkList L , int i ) {
DuLinkList p = L , q = L ;
int k = 0 ;
if ( i< 1 || i > GetLength( L ) )
{
printf ( "删除数据位置错误 \n" ) ;
}
for( k = 1 ; k < i ; k++ ) //找到要删除的数据的前一个节点.
p = p -> next ;
q = p -> next ;
p -> next = q -> next ;
q -> next -> prior = p ;
free ( q ) ;
printf("\n删除%d位置的数据成功\n");
}
void DeleteElem ( DuLinkList L , ElemType e ){
DuLinkList p = L ;
int i = 0 ;
while( p->next ){
p = p -> next ;
i ++ ;
if( p -> data == e )
{
DeleteIndex( L , i);
}
}
}
void Traverse(DuLinkList L){ //正向遍历
DuLinkList p = L ;
printf ( " \n正向遍历数据 : \n" );
while( p -> next )
{
p= p-> next ;
printf ( " %d\t " , p -> data );
}
}
void Display (DuLinkList L){ //反向遍历
DuLinkList p = L ;
printf ( "\n 反向遍历数据 : \n" );
while( p -> next )
{
p = p -> next ;
}
while (p -> prior -> prior )
{
printf(" %d\t " , p->data ) ;
}
}