#include
typedef struct dlist{
int element;
struct dlist *next;
struct dlist *prev;
}NODE;
NODE *createNode(int item){
NODE *newNode=NULL;
newNode = (NODE *)malloc(sizeof(NODE));
newNode->element=item;
newNode->next=NULL;
newNode->prev=NULL;
return newNode;
}
NODE *insertNodeHead(NODE *head,int item){
NODE *newNode = NULL;
newNode = createNode(item);
if(head == NULL)
return newNode;
newNode->next = head;
head->prev = newNode;
return newNode;
}
NODE *insertNodeTail(NODE *head,int item){
NODE *newNode = NULL,*runNode = head;
newNode = createNode(item);
if(head == NULL)
return newNode;
while(runNode->next!=NULL)
runNode = runNode->next;
runNode->next = newNode;
newNode->prev = runNode;
return head;
}
NODE *insertNodeBetween(NODE *head,int item,int position){
NODE *newNode =NULL,*runNode = head;
newNode = createNode(item);
if(head ==NULL){
return newNode;
}
else{
while(runNode != NULL && runNode->element!=position)
runNode = runNode->next;
if(runNode == NULL)
printf("position not found [%d]\n",position);
else {
if(runNode->prev ==NULL){ //insert head node
runNode->prev = newNode;
newNode->next = runNode;
head = newNode;
}else{
newNode->next = runNode;
newNode->prev = runNode->prev;
runNode->prev = newNode;
newNode->prev->next = newNode;
}
}
}
return head;
NODE *deleteNode(NODE *head,int item){
NODE *runNode = head;
while(runNode != NULL && runNode->element!=item)
runNode = runNode->next;
if(runNode == NULL){
printf("data not found [%d]\n",item);
}
else {
if(runNode->prev == NULL) { //delete head node
head = head->next; //move next
head->prev = NULL;
}
else {
runNode->prev->next = runNode->next ;
if(runNode->next != NULL)
runNode->next->prev = runNode->prev ;
}
free(runNode);
}
return head;
}
void displayNode(NODE *head){
NODE *runNode = head;
while (runNode != NULL){
printf("[%d]->",runNode->element);
runNode = runNode->next;
}
printf("NULL\n");
}
void main(){
NODE *head=NULL;
printf("insert head node 10 15 90\n");
head = insertNodeHead(head,10);
head = insertNodeHead(head,15);
head = insertNodeHead(head,90);
displayNode(head);
printf("insert tail node 300 400\n");
head = insertNodeTail(head,300);
head = insertNodeTail(head,400);
displayNode(head);
printf("insert between node (955,300) (990,90) (940,400) \n");
head = insertNodeBetween(head,955,300);
head = insertNodeBetween(head,990,90);
head = insertNodeBetween(head,940,400);
head = insertNodeBetween(head,940,500);
displayNode(head);
printf("delete node 90 15 400 500\n");
head = deleteNode(head,90);
head = deleteNode(head,15);
head = deleteNode(head,400);
head = deleteNode(head,500);
displayNode(head);
}
No comments:
Post a Comment