Go to the end of the list.
While node-%26gt;prev != NULL
{
print value
node = node-%26gt;prev
}
Write a non-recursive function in 'C' Programming language to reverse a doubly linked list.?
Here is an example:
#include %26lt;stdio.h%26gt; /* for printf */
#include %26lt;stdlib.h%26gt; /* for malloc */
typedef struct ns {
int data;
struct ns *next;
} node;
node *list_add(node **p, int i) {
/* some compilers don't require a cast of return value for malloc */
node *n = (node *)malloc(sizeof(node));
if (n == NULL)
return NULL;
n-%26gt;next = *p;
*p = n;
n-%26gt;data = i;
return *p;
}
void list_remove(node **p) { /* remove head */
if (*p != NULL) {
node *n = *p;
*p = (*p)-%26gt;next;
free(n);
}
}
node **list_search(node **n, int i) {
while (*n != NULL) {
if ((*n)-%26gt;data == i) {
return n;
}
n = %26amp;(*n)-%26gt;next;
}
return NULL;
}
void list_print(node *n) {
if (n == NULL) {
printf("list is empty\n");
}
while (n != NULL) {
printf("print %p %p %d\n", n, n-%26gt;next, n-%26gt;data);
n = n-%26gt;next;
}
}
int main(void) {
node *n = NULL;
list_add(%26amp;n, 0); /* list: 0 */
list_add(%26amp;n, 1); /* list: 1 0 */
list_add(%26amp;n, 2); /* list: 2 1 0 */
list_add(%26amp;n, 3); /* list: 3 2 1 0 */
list_add(%26amp;n, 4); /* list: 4 3 2 1 0 */
list_print(n);
list_remove(%26amp;n); /* remove first (4) */
list_remove(%26amp;n-%26gt;next); /* remove new second (2) */
list_remove(list_search(%26amp;n, 1)); /* remove cell containing 1 (first) */
list_remove(%26amp;n-%26gt;next); /* remove second to last node (0) */
list_remove(%26amp;n); /* remove last (3) */
list_print(n);
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment