# include <iostream> # include <stdio.h>
# include <stdlib.h> using namespace std; typedef struct LNode { int data; struct LNode * next; } LNode, * LinkList; bool InitList ( LinkList & L) { L = ( LNode * ) malloc ( sizeof ( LNode) ) ; if ( L== NULL ) { return false ; } L-> next = NULL ; return true ;
}
bool empty ( LinkList & L) { return ( L-> next== NULL ) ;
} bool insert ( LinkList & L, int i, int e) { if ( i< 1 ) { return false ; } LNode * p = L; int j = 0 ; while ( p!= NULL && j< i- 1 ) { p= p-> next; j++ ; } if ( p == NULL ) { return false ; } LNode * s = ( LNode * ) malloc ( sizeof ( LNode) ) ; s-> data = e; p-> next = s-> next; p-> next= s; return true ;
} bool deleteN ( LinkList & L, int i , int & e) { if ( i< 1 ) return false ; LNode * p = L; int j = 0 ; while ( p-> next!= NULL && j< i- 1 ) { p= p-> next; j++ ; } if ( p == NULL ) { return false ; } if ( p-> next == NULL ) { return false ; } LNode * q = p-> next; e = q-> data; p-> next = q-> next; free ( q) ; } int main ( ) { LinkList L; InitList ( L) ; LNode * r= L; for ( int i = 1 ; i <= 5 ; i ++ ) { insert ( L, i, i) ; } while ( r-> next) { printf ( "%d " , r-> next-> data) ; r = r-> next; } int e = 0 ; deleteN ( L, 2 , e) ; printf ( "\n%d 被删除\n" , e) ; LNode * w= L; while ( w-> next) { printf ( "%d " , w-> next-> data) ; w = w-> next; } free ( r) ; return 0 ;
}