How do display the list in single linked list form last to first

Showing Answers 1 - 4 of 4 Answers

Gyan Prakash

  • Aug 10th, 2006
 

display(node *p){ if(p->next==NULL) printf("%d ",p->info); else { display(p->next); printf("%d ",p->info); }}

  Was this answer useful?  Yes

Nilanjan Mukhopadhyay

  • Aug 14th, 2006
 

void reverse_list(Node**hp)
 {
  Node*p,*q,*r;
  if(*hp==NULL || (*hp)->next==NULL)
   {
    printf("nReversing is not possible...");
    getch();
    return;
   }
   r=NULL;q=*hp;p=q->next;
   while(p!=NULL)
   {
    q->next=r;
    r=q;
    q=p;
    p=p->next;
   }
   q->next=r;
   *hp=q;
 }

//hp=head pointer

p,q,r are the nodes of a linklist

should be called from the main as

reverse_list(&head);

head= head pointer in main func

  Was this answer useful?  Yes

Avinash

  • Sep 8th, 2006
 

typedef struct _node
{
 char *data;
 struct _node *next;
} node ;
node *head=NULL;

main()

{

LinkedList();

}


void LinkedList()
{
 AddNode("hello");
 AddNode("how");
 AddNode("are");
 AddNode("you");
 AddNode("?");
 PrintList();
 ReverseList();
 PrintList();

}
void ReverseList()
{
 node *prev, *curr, *next;
 prev=NULL;
 curr=head;
 next=head->next;

 while( NULL != curr )
 {
  curr->next=prev;
  prev=curr;
  curr=next;
  if ( curr != NULL ) next=curr->next;
 }
 head=prev;
}


void PrintList()
{
 node *temp;

 /* Traverse*/
 temp=head;
 while ( NULL != temp )
 { 
  printf("[%s]->",temp->data);
  temp=temp->next;
 }
 printf("NULLn");
}

int AddNode(char *data)
{
 node * temp=NULL;

 /* If first node */
 if ( NULL == head )
 {
  if ( NULL == (head = (node *) malloc(sizeof(struct _node))) )
  {
   printf("error allocating memory for new node n");
   return 1;
  }
  
  if ( NULL == (head->data = (char *) malloc(sizeof(data))))
  {
   printf("error allocating memory for node datan");
   return 1;
  }

  strcpy(head->data,data);
  head->next=NULL;
  return 0;
 }

 /* Goto last node */
 temp=head;
 while ( NULL != temp->next )
 { 
  temp=temp->next;
 }

 /* Allocate memory for last node */
 if ( NULL == (temp->next = (node *) malloc(sizeof(struct _node))) )
 {
  printf("error allocating memory for new node n");
  return 1;
 }
 
 if ( NULL == (temp->next->data = (char *) calloc(DATA_SIZE,sizeof(char))) )
 {
  printf("error allocating memory for node datan");
  return 1;
 }

 strcpy(temp->next->data,data);
 temp->next->next=NULL;
 return 0;


 

  Was this answer useful?  Yes

mritunjay

  • Sep 25th, 2006
 

excellent answer

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions