Presentation is loading. Please wait.

Presentation is loading. Please wait.

Double Linked List Operations Dr. David Tsai 2010/4/12.

Similar presentations


Presentation on theme: "Double Linked List Operations Dr. David Tsai 2010/4/12."— Presentation transcript:

1 Double Linked List Operations Dr. David Tsai 2010/4/12

2 void createDList (int len, int*array) { int i; DList newnode, before; first = (DList) malloc (sizeof (DNode) ); first->data = array[0]; first->previous = first->next = NULL; before = first /*now = first; */ for (i = 1; i < len; i++) { newnode = (DList) malloc (sizeof(Dnode) ); newnode->data = array[i]; newnode->next = NULL; newnode->previous = before; before->next = newnode; before = newnode; } C /

3 60 first NULL before 50 newnode NULL 40 NULL

4 void printDList () { DList now = first; while (now! = NULL) { back = now; printf ( %d, now->data); now = now->next; } printf ( \n ); now = back->previous; while (now! = NULL) { back = now; printf ( %d, now->data); now = now->previous; } printf ( \n ); }

5 now 60 first NULL 50 NULL 40 back

6 void deleteDNode (DList ptr) { if (ptr->previous == NULL) { first = first->next; first->previous = NULL; } else { if (ptr->next == NULL) { ptr->previous->next = NULL; } else{ ptr->previous->next = ptr->next; ptr->next->previous = ptr->previous; } free (ptr); }

7 ptr 60 first NULL 50 NULL NULL To Delete First Node

8 ptr 60 first NULL 50 NULL To Delete Last Node NULL

9 ptr 60 first NULL 50 NULL To Delete a Middle Node

10 void insertDNode (DList ptr, int d) { DList newnode = (DList) malloc (sizeof (DNode) ) ; newnode->data = d; newnode->next = newnode->previous = NULL; if (first == NULL) { first = newnode; } if (ptr == NULL) { newnode->previous = NULL; newnode->next = first; first->previous = newnode; first = newnode; } else { if (ptr->next == NULL) { ptr->next = newnode; newnode->previous = ptr; newnode->next = NULL; } else { ptr->next->previous = newnode; newnode->next = ptr->next; newnode->previous = ptr; ptr->next = newnode; } } }

11 50 first = 40 newnode == = = 60 ptr = = To Create a Double Linked List To Insert a New Node at Front of the First Node To Insert a New Node at End of the Last Node

12 50 first 40 newnode = = = 60 ptr = 55 To Insert a New Node into the Middle of the List


Download ppt "Double Linked List Operations Dr. David Tsai 2010/4/12."

Similar presentations


Ads by Google