简体   繁体   中英

Reverse a linked list using recursion in cpp

I'm getting empty list as output, Can anyone help me out with this.

ListNode* reve(ListNode* L,ListNode* t){
        if(L->next==NULL){
            t=L;
            print(t);
            return L;
        }
        ListNode* k = reve(L->next,t);
        k->next=L;
        L->next=NULL;
        return L;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode* temp=NULL;
        reve(head,temp);
        return temp;
    }

The logic makes sense, it's just that the printing of the list should come after the list has been reversed. You should remove print(t) and instead put print(temp) after the call to reve() in the bottom function.

t should also be a pointer to a pointer in order to change the value of the passed-in pointer:

ListNode* reve(ListNode* L, ListNode** t) {
  if (L->next == NULL) {
    *t = L;
    return L;
  }
  ListNode* k = reve(L->next, t);
  k->next = L;
  L->next = NULL;
  return L;
}

ListNode* reverseList(ListNode* head) {
  if (!head) return NULL;
  ListNode* temp;
  head = reve(head, &temp);
  print(temp);
  return newHead;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM