Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Reversed linked list iteratively

I am currently writing a program that has a function that prints a linked list in reverse.

I need to print the reverse of what this code prints using the iterative approach.

EDIT: It is a single linked list.

Thanks in advance.

void print_backward_iteration(NODE *ptr) {
    NODE *last, *current;

    last = NULL;

    printf("\n");

    while (ptr != last) {
        current = ptr;

        while (current -> next != last) {
            current= current -> next;
        }

        printf("%d  ", current -> data);
        last = current;
    }

    printf("\n");

}

Here is my complete code:

#include <stdio.h>
#include <stdlib.h>

/* declaration of structure */
typedef struct node {
    int data;
    struct node *next;
} NODE;

/* declaration of functions */
NODE* insert_node(NODE *ptr, NODE *new);
NODE* find_node(NODE *ptr, int n);
NODE* delete_node(NODE *ptr, int n, int *success_flag_ptr);
void print_backward_iteration(NODE *ptr);
void print_backward_recursion(NODE *ptr);

int main(int argc, char *argv[]) {
    int choice, x, flag_success;
    NODE *ptr, *new, *result;

    ptr = NULL;

    do {
        printf("\n1.\tInsert Integer into linked list\n");
        printf("2.\tFind integer in linked list\n");
        printf("3.\tDelete integer from linked list\n");
        printf("4.\tPrint out integers backward using the iterative strategy\n");
        printf("5.\tPrint out integers backward using the recursive strategy\n");
        printf("6.\tQuit\n");
        printf("\nEnter 1,2,3,4,5, or 6: ");
        scanf("%d", &choice);

        switch(choice) {
        case 1:
            printf("\nPlease enter an integer: ");
            scanf("%d", &x);
            new = (NODE *)malloc(sizeof(NODE));
            new->data = x;
            ptr = insert_node(ptr, new);
            printf("\nNode Inserted with value of %d.\n", ptr->data);
            break;

        case 2:
            printf("\nPlease enter an integer: ");
            scanf("%d", &x);
            result = find_node(ptr, x);

            if (result == NULL) {
                printf("\nValue could not be found.\n");
            } else {
                printf("\nValue %d was found.\n", x);
            }
            break;

        case 3:
            printf("\nPlease enter an integer: ");
            scanf("%d", &x);
            ptr = delete_node(ptr, x, &flag_success);

            if (result == NULL) {
                printf("\nValue could not be found.\n");
            } else {
                printf("\nValue %d was deleted.\n", x);
            }
            break;

        case 4:
            print_backward_iteration(ptr);
            break;

        case 5:
            printf("\n");
            print_backward_recursion(ptr);
            printf("\n");
            break;

        case 6:
            printf("\nThank you for using this program.\n");
            break;

        default:
            printf("\nInvalid Choice. Please try again.\n");
            break;
        }
    }
    while (choice != 6);

    printf("\n*** End of Program ***\n");
    return 0;
}

/* definition of function insert_node */
NODE* insert_node(NODE *ptr, NODE *new) {
    new -> next = ptr;
    return new;
}

/* definition of function find_node */
NODE* find_node(NODE *ptr, int n) {
    while (ptr != NULL) {
        if (ptr->data == n) {
            return ptr;
        } else {
            ptr = ptr->next;
        }
    }

    return NULL;
}

/* definition of function delete_node */
NODE* delete_node(NODE *ptr, int n, int *success_flag_ptr) {
    NODE *temp = NULL;

    if (ptr == NULL) {
        *success_flag_ptr = 0;
        return NULL;
    }

    if (ptr -> data == n) {     
        temp = ptr->next;  
        free(ptr);         
        *success_flag_ptr = 1;
        return temp;
    } else
        ptr->next = delete_node(ptr->next,n,success_flag_ptr); 

    return ptr;
}

/* definition of function print_backward_iteration */
void print_backward_iteration(NODE *ptr) {
    NODE *last, *current;

    last = NULL;

    printf("\n");

    while (ptr != last) {
        current = ptr;

        while (current != last) {
            current =  current -> next;
        }

        printf("%d  ", current -> data);
        last = current -> next;
    }

    printf("\n");
}

/* definition of function print_backward_recursion */
void print_backward_recursion(NODE *ptr) {
    NODE *last, *current;

    last = NULL;

    while (ptr != last) {
        current = ptr;
        printf("%d  ", current -> data);
        print_backward_recursion(current -> next);
        last = current;
    }
}
like image 972
Puzzledplane Avatar asked Nov 30 '12 23:11

Puzzledplane


2 Answers

UPDATE - I'm keeping the code below on the off-chance someone looking to actually reverse-print a linked list sans-recursion using any of the methods provided can get some kinda of use out of them. In the meantime, the OP's real question was effectively:

"How to I print a linked list in head-to-tail order?"

Who saw that coming? Anyway,

void print_node_list(const NODE* p)
{
    printf("\n");
    for (;p;printf("%d ",p->data),p=p->next);
    printf("\n");
}

Yeah, it was that simple.


Now-Near-Worthless Reverse-Print Discussion

Complying with your requirement of this being an iterative solution, and more importantly, assuming your lists order unchanged after this operation is complete, you can either:

  1. Manage a node pointer stack in your iteration, pushing pointers as you single-pass the list traveral, then popping pointers off the stack to print the reverse. Requires two passes (one through the list, one through the stack). There are multiple options for managing such a stack; two are presented below.

  2. Perform a simple reverse/print/reverse. Requires three passes (one for the reverse, one for the print, and one for the undo-reverse).

The former of these offers the advantage of keeping the list constant (no node-reversals are done) at the price of the space required to manage the stack. The latter of these offers the benefit of no additional space requirements, but at the cost of three-passes on the list, and requiring the list be allowed to be modified, though temporarily.

Which you choose is up to you.

Local Stack Implementation: (2 passes, 2*N*sizeof(pointer) space)

void print_reverse_node_list(const NODE* head)
{
    struct stnode
    {
        struct stnode* next;
        const NODE* node;
    } *st = NULL;

    while (head)
    {
        struct stnode* p = malloc(sizeof(*p));
        if (p)
        {
            p->next = st;
            p->node = head;
            st = p;
            head = head->next;
        }
        else
        {
            perror("Could not allocate space for reverse-print.");
            exit(EXIT_FAILURE);
        }
    }

    // walks stack, popping off nodes and printing them.
    printf("\n");
    while (st)
    {
        struct stnode* p = st;
        st = st->next;
        printf("%d ", p->node->data);
        free(p);
    }
    printf("\n");
}

Another Local Stack Implementation (2-passes, N*sizeof(pointer) space)

void print_reverse_node_list(const NODE* head)
{
    NODE const **ar = NULL;
    size_t i=0;
    while (head)
    {
        // reallocate pointer array
        NODE const **tmp = realloc(ar, ++i * sizeof(*tmp));
        if (tmp)
        {
            ar = tmp;           // remember new array
            ar[i-1] = head;     // last index gets the ptr
            head = head->next;  // advance to next node
        }
        else
        {
            perror("Could not allocate space for reverse-print.");
            exit(EXIT_FAILURE);
        }
    }

    // print nodes from [i-1] to [0]
    printf("\n");
    for (; i!=0; printf("%d ", ar[--i]->data));
    printf("\n");
    // don't forget to release the block (NULL is ok)
    free(ar);
}

Reverse/Print/Reverse Implementation: (3 passes, no additional space)

// print a node list.
void print_node_list(const NODE* p)
{
    printf("\n");
    for (;p;printf("%d ",p->data),p=p->next);
    printf("\n");
}

// reverses a linked list in-place.
void reverse_node_list(NODE **headp)
{
    if (!headp || !*headp)
        return;

    NODE *ptr = *headp, *next = NULL, *prev = NULL;
    while (ptr)
    {
        next = ptr->next;      // remember next node (1)
        ptr->next = prev;      // wire next to prev
        prev = ptr;            // set prev to current
        ptr = next;            // move to remembered next (see 1)
    }

    *headp = prev;
}

void print_reverse_node_list(NODE* head)
{
    reverse_node_list(&head);
    print_node_list(head);
    reverse_node_list(&head);
}
like image 170
WhozCraig Avatar answered Sep 22 '22 00:09

WhozCraig


void print_Linked_List_iteration(NODE *ptr)
{

  printf("\n");

  while (ptr != NULL)
  {

      printf("%d  ", ptr->data);
      ptr = ptr->next;
  }

  printf("\n");

}
like image 38
Adeel Ahmed Avatar answered Sep 18 '22 00:09

Adeel Ahmed