Print integers in reverse order using LinkedLists

| December 15, 2010 | 0 Comments

Scenario:

You need to make program in C that can accept numbers from user and print integers in reverse order using LinkedLists.

Solution:

There are three functions:

  • Insert – Insert each number or integer into LinkedList from user.
  • Reverse – Reverse each number in linkedlist starting from first number in linkedlist.
  • PrintList – Print each number in linkedlist to output screen.

For rest check out code snippet provided below.

Code Snippet:

# include
# include
# include  /* For LinkedList */

// Designing struct named "node"
struct node
{
 int data;
 struct node *link; // link pointer pointing to struct node
};

struct node *insert(struct node *p, int n)
{
 struct node *temp; // temp pointer pointing to struct node

 // if the existing list is empty then insert a new node as the
 // starting node
 if(p==NULL)
 {
  // creates new node data value passes as parameter
  p=(struct node *)malloc(sizeof(struct node));

  if(p==NULL)
  {
   printf("Error\n");
   exit(0);
  }

  p-> data = n; // p pointer pointing to data of struct start
  p-> link = NULL;
 }
 else
 {
  temp = p;

  // traverses the existing list to get the pointer to the last node of it
  while (temp-> link != NULL)
  temp = temp-> link;
  temp-> link = (struct node *)malloc(sizeof(struct node));

  //creates new node using data value passes as parameter and puts its
  //address in the link field of last node of the existing list
  if(temp -> link == NULL)
  {
   printf("Error\n");
   exit(0);
  }

  temp = temp-> link;
  temp-> data = n;
  temp-> link = NULL;
 }
 return (p);
}

// Function for reversing integer list
struct node *reverse(struct node *p)
{
    struct node *prev, *curr;
 prev = NULL;
 curr = p;
 while (curr != NULL)
 {
  p = p-> link;
  curr-> link = prev;
  prev = curr;
  curr = p;
 }
 return(prev);
}

// Function to print on screen
void printlist ( struct node *p )
{
 while(p!= NULL)
 {
  printf("%d\n",p->data);
  p=p->link;
 }
}

// Main function
void main()
{
 int n;
 int x;

 struct node *start = NULL ;
 printf("Enter the number of nodes to create: \n");
 scanf("%d",&n);
 while ( n-->0 )
 {
  printf( "Enter the data values to be placed in a node\n");
  scanf("%d",&x);
  start = insert ( start, x );
 }

 printf("\nDETAILS OF CREATED LIST:\n");
 printlist (start);
 start=reverse(start);
 printf("\nREVERSE LIST OF NUMBERS:\n");
    printlist(start);
}

Tags:

Category: .NET

Leave a Reply

%d bloggers like this: