change a linked list to insert right instead of left

Hello all, I have a linked list that inserts and removes left which of course means the data I am reading in from a file prints backwards. I have tried everything I can think of inorder to have it print in order. The closest I have come so far is printing out the first item, but then it ends. Any help would be greatly appreciated.


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  #include <iostream>
#include <stdlib.h>

using namespace std;

struct Node
  {
    int info;
    Node * next;
  };

Node *head=NULL, *p, *t;
void Insert_Left(Node * &head, Node *p)
  {
    if (!head)
      {
        //cout << p->info << ' ';
        head = p;
      }
    else
      {
        p->next = head;
        //cout << p->info << ' ';
        head = p;
      }
  }

Node * Remove_Left(Node *&root)
  {
    Node * p;
    p = root;
    if (root)
      {
        root = p->next;
      }
    return p;
  }

int empty()
  {
    return head == NULL;
  }


#if __INCLUDE_LEVEL__ < 1
int main()
  {
    int i;

    for (i = 0; i < 5; i++)
      {
        p = new Node;
        p->info = i;
        p->next = NULL;
        Insert_Left(head, p);
      }
    cout << endl;

    t = head;
    while (t)
      {
        cout << t->info << ' ';
        t = t->next;
      }
    cout << endl;
  }

#endif
closed account (D80DSL3A)
You need to maintain a pointer to the last Node in the list.
Declare a Node * tail; and use it in BOTH insert functions.
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
Node *head=NULL, tail=NULL, *p, *t;
void Insert_Left(Node * &head, Node * &tail,  Node *p)
  {
    if (!head)
      {
        head = tail = p;// assign both when 1st Node created.
      }
    else
      {
        p->next = head;
        //cout << p->info << ' ';
        head = p;
      }
  }

void Insert_Right(Node * &head, Node * &tail, Node *p)
  {
    if (!head)
      {
        head = tail = p;// assign both when 1st Node created.
      }
    else
      {
        tail->next = p;
        //cout << p->info << ' ';
        tail = p;
      }
  }

This tail Node* won't allow you to Remove_Right though (trying to anticipate your next question). You would have to iterate through the list each time to do that.
Thank you sir!
Topic archived. No new replies allowed.