Welcome, %1$s. Please login or register.

April 27, 2017, 10:23:34 PM
: 1
: How do you write a function that can reverse a linked-list? (Cisco System)  ( 4296 )
« : May 15, 2007, 08:18:04 PM From Hari»



How do you write a function that can reverse a linked-list? (Cisco System)


How do you write a function that can reverse a linked-list? (Cisco System)

 
Liked It? Share it!

              


« #1 : May 15, 2007, 08:19:25 PM From mohank»

void reverselist(void)
{
   if(head==0)
      return;
   if(head->next==0)
      return;
   if(head->next==tail)
   {
      head->next = 0;
      tail->next = head;
   }
   else
   {
      node* pre = head;
      node* cur = head->next;
      node* curnext = cur->next;
      head->next = 0;
      cur->next = head;      for(; curnext!=0; )
      {
         cur->next = pre;
         pre = cur;
         cur = curnext;
         curnext = curnext->next;
      }      curnext->next = cur;
   }
}
« #2 : November 20, 2007, 06:34:49 PM From iammilind»

Answer is according to the fact that only head of the singly link list is given.

struct List{ ...; List *next; }

void Reverse_Link_List (List *head) // head is not null
{
   List *tail = head;
 
   while( head->next ) head = head->next;
// now 'tail' is at head of link list and 'head' is at tail of link list

    while( tail != head )
    {
        List *temp = tail;
        tail = tail->next;

        temp->next = head->next;
        head->next = temp;
    }
}
// now 'head' is at the head of reversed link list, so need not return List*
« #3 : November 10, 2010, 10:46:48 AM From prayas»

void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

Read more at http://study.tryandfun.com/
: 1
« previous next »

 

Best RatedList All>>



Latest
Random



SMF 2.0.10 | SMF © 2015, Simple Machines | Contact Webmaster | OnlineFunDb.com © 2009/10 | Legal Disclaimer