Help with Reverse Linked List Function

Hello,

I need some help on a function I am writing to return a new linked-list which is the current one reversed.

This code is given as a starting point for the function:
1
2
3
4
	LList reverse() const{
		// TODO: Fill me in
		return LList(); // Remove me!
	}


Here is some of the declarations of the header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#ifndef LLIST_H
#define LLIST_H
#include <ostream>
#include <stdexcept>

#define int int

using namespace std;

struct node_t {
    int data;
    node_t* next;
};

LList(){
        head = NULL;
    }

    ~LList(){
        clear();
    }

    LList(const LList& other){
        // Do the same as the default constructor
        head = NULL;
        // Check if the other LList is empty
        if(other.head == NULL){
            return;
        }
        // Not empty?  Iterate through the other list
        // and push_back on myself.
        node_t* temp = other.head;
        while(temp){
            push_back(temp->data);
            temp = temp->next;
        }
    }
}




The test code which the function should work with is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  LList a;
  a.push_back(5);
  a.push_back(6);
  a.push_back(7);
  LList b = a.reverse();
  cout << a.size() << "should = 3" << endl;
  cout << b.size() << "should = 3" << endl;

  cout << a.getAt(0) << "should = 5" << endl;
  cout << b.getAt(0) << "should = 7" << endl;
  cout << a.getAt(1) << "should = 6" << endl;
  cout << b.getAt(1) << "should = 6" << endl;
  cout << a.getAt(2) << "should = 7" << endl;
  cout << b.getAt(2) << "should = 5" << endl;

Note: getAt(int position) simply returns the value in the linked list at the position.

And this is what I have so far. This code creates the new linked list in the reverse order but deletes the first linked list which is being reversed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    LList reverse() const{
        LList ret;
        node_t *current, *prev, *next;
        current = head;
        prev = NULL;

        while(current != NULL)
        {
            next = current->next;
            current->next = prev;
            prev = current;
            current = next;

        }
        ret.head = prev;
        return ret;

    }


This function cannot use recursion however.


Any help would be greatly appreciated.
Thanks.

Last edited on
Topic archived. No new replies allowed.