How to insert 25 at the beginning of the the line

How would you add 25 at the start of the line instead of next to 10.
in the same type of cpp. the c-ish cpp.
like:
10 15 20 25
25 10 15 20 25
instead of:
10 15 20 25
10 25 15 20 25
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
#include <iostream>
#include <string>

using namespace std;

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

Node * head;

void PrintAll(){
    Node * temp = head;
    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}
void Append(int A){
     Node * temp = new Node;
     temp->data = A;
     temp->next = NULL;
     if(head == NULL){
        head = temp;
        return;
     }
     Node * temp2 = head;
     while(temp2->next != NULL){
          temp2 = temp2->next;
     }
        temp2->next = temp;

}
int main(){
    head = NULL;
    Append(10);
    Append(15);
    Append(20);
    Append(25);

    PrintAll();
    Node * temp = new Node;
    temp->data = 25;
    temp->next = head->next;
    head->next = temp;
    PrintAll();

     return 0;
}
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
#include <iostream>
#include <string>

using namespace std;

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

	Node() {}
	Node(int d) : data(d) {}
};

Node* head {};

void PrintAll() {
	for (auto temp {head}; temp != nullptr; temp = temp->next)
		cout << temp->data << " ";

	cout << '\n';
}

void Append(int A) {
	Node* temp {new Node(A)};

	if (head == nullptr) {
		head = temp;
		return;
	}

	auto temp2 {head};

	for (; temp2->next != nullptr; temp2 = temp2->next);

	temp2->next = temp;
}

int main() {
	Append(10);
	Append(15);
	Append(20);
	Append(25);

	PrintAll();

	auto temp {new Node(25)};

	temp->next = head;
	head = temp;

	PrintAll();
}


NOTE that allocated memory is not being freed before the program exits. his is bad practice. All allocated memory should be freed within the program.


10 15 20 25
25 10 15 20 25

Topic archived. No new replies allowed.