Create a reverse LinkedList in C++ from a given LinkedList

前端 未结 10 985
温柔的废话
温柔的废话 2020-11-30 08:37

I\'m having some trouble create a linkedlist in reverse order from a given linkedlist.

I come from a java background, and just started doing some C++.

Can yo

10条回答
  •  情歌与酒
    2020-11-30 08:42

    The sample below use the recursion for reversing a linklist. I asked this Qs at a job interview. This has been tested and works. ListElem is the node.

    void LinkList::reverse()
    {
    if(pFirst == NULL) return;
    ListElem* current = pFirst;
    revCur(NULL, current, NULL);
    }
    
    void LinkList::revCur(ListElem *prev, ListElem* current, ListElem* next)
    {
     //   ListElem *prev = NULL, *current = NULL, *next = NULL;
     if ( current != NULL )
     {
         next = current->next;
         current->next = prev;
         prev = current;
         current = next;
         pFirst = prev;
         this->revCur(prev,current,next);
        }
    }
    

提交回复
热议问题