// inserts at the specified index. // example: insert(2) would be third item in the list. int ListInsertAt( list *l, void *data, int pos ) { if ( l == NULL || data == NULL ) return 0; listNode *node = l->head; if ( pos <= 0 ) { ListInsertAtFront( l, data ); return 1; } else if ( pos > l->itemCount ) { ListInsertAtEnd( l, data ); return 1; } for( int i = 0; i < l->itemCount; i++ ) { if ( i == pos ) { listNode *prev = node->prev; listNode *newNode = ListCreateNode( data ); node->prev = newNode; // insert before this. prev->next = newNode; // tell prev node this new node follows it. newNode->prev = prev; newNode->next = node; l->itemCount++; } node = node->next; } return 1; }
void ListInsert(ListNode *Node, void *Data) { while (Node->Next != NULL) Node = Node->Next; Node->Next = ListCreateNode(); (Node->Next)->Prev = Node; Node = Node->Next; Node->Data = Data; Node->Next = NULL; }
list *ListCreate( void *data ) { list *l = malloc( sizeof ( list ) ); listNode *node = ListCreateNode( data ); // single item right node->next = node; node->prev = node; // update list ptrs. l->head = node; l->tail = node; l->itemCount = 1; return l; }
// inserts as head int ListInsertAtFront( list *l, void *data ) { if ( l == NULL || data == NULL ) return 0; listNode *node = ListCreateNode( data ); node->prev = l->tail; node->next = l->head; l->head->prev = node; l->head = node; l->itemCount++; return 1; }
// inserts as tail int ListInsertAtEnd( list *l, void *data ) { if ( l == NULL || data == NULL ) return 0; listNode *node = ListCreateNode( data ); node->prev = l->tail; // adding to end so tail is before this node->next = l->head; // circally doubly linked list l->tail->next = node; // current tail points to this new node l->tail = node; // set tail ptr to this new node. l->itemCount++; return 1; }