Inserting element at nth position in Linked List

Jul 23, 2018 at 8:32am
The function InsertAtnthPosition()
is not executing properly at the program crashes. I have yet to add deallocation statements. What is the error in that function? Anyways i am posting the code for the whole program which i am trying to build.

The function mentioned after executing it's last statement shows this : Process Returned -1073741819 (0xc0000005)

I am using code blocks as i dont have my laptop right now,usually i use eclipse or VSCode.
Is it running out memory? Or is it something else?
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
  #include<iostream>
#include<stdlib.h>
using namespace std;
void InsertAtnThPosition();
void InsertAtBeginning();
void Print();
void Exit();
struct Node
{
    int data;
    Node *link;
};
Node *head,*temp2;
int main()
{
    head = NULL; // List Is Empty
    int choice;
    char ans = 'y';
    do
    {
        cout << "\n1.Insert At Beginning\n2.Insert at nTH Position\n3.Delete An Element\n4.Print The Linked List\n5.Exit\n";
        cin >> choice;
        if (choice == 1)
        {
            InsertAtBeginning();
        }
        else
            if (choice == 2)
        {
            InsertAtnThPosition();
        }
        else
            if (choice == 4)
        {
            Print();
        }
        else
            if (choice == 5)
        {
            Exit();
        }

    }
    while (ans == 'y' || ans == 'Y');
    return 0;
}
void InsertAtBeginning()
{
    int x;
    cout << "\nEnter The Data:";
    cin >> x;
    Node *temp = new Node;
    temp -> data = x;
    temp -> link = NULL;
        if (head == NULL)
        {
            head = temp;
        }
        else
            if (head!= NULL)
        {
            temp -> link = head ;
            head =temp;
        }
}
void InsertAtnThPosition()
{
    int num,pos;
    Node *ptr = new Node;
    cout << "\nEnter The Data:";
    cin >> num;
    cout <<"\nEnter The Position where the Value is to be inserted:";
    cin >> pos;
    ptr -> data = num;
    ptr -> link = NULL;
        if (pos == 1)
           {
            ptr -> link = head; // Set the link of the new node to the node where head points
            head = ptr; // store the address of new node to be inserted at 1th position in the head node
           }
        else
            temp2 = head;
        for (int i = 0 ; i < pos -2 ; ++pos)
        {
            temp2 = temp2 -> link; // temp 2 is already pointing at first node
        }
        ptr -> link = temp2 ->link; /*sets the link of new node the next node */
        temp2 ->link = ptr; /* sets the link previous node to the new node */
        return ;
}
void Print()
{
 Node *ptr;
 ptr = head;
 cout << "\nNow The Linked List Is:\n";
    while(ptr!= NULL)
    {
        cout << endl << ptr -> data;
        ptr = ptr -> link;
    }
}

void Exit()
{
    exit(1);
}
Last edited on Jul 23, 2018 at 8:37am
Jul 23, 2018 at 9:07am
1
2
3
4
	for (int i = 0; i < pos - 2; ++pos)
	{
		temp2 = temp2->link; // temp 2 is already pointing at first node
	}


temp2 is bad here. I discovered this by running the program under a debugger. Learn to use the debugger.

You've written an infinite loop here. This for loop will go on and on until pos overflows and wraps back around to a negative number, or until temp2 is bad it crashes.
Last edited on Jul 23, 2018 at 9:12am
Jul 23, 2018 at 9:23am
Ah,I quite didn't get you here,sorry,What do you mean by saying that temp2 is bad? and how is it an infinite loop? It will break once i >= pos- 2. Sorry if i m being dumb,i am coding in c++ after long time,am refreshing my data structures concepts.

Last edited on Jul 23, 2018 at 9:26am
Jul 23, 2018 at 9:28am
It will break once i >= pos- 2.


And when will that happen? What happens, in your for loop, to the value of i? What happens, in your for loop, to the value of pos?
Last edited on Jul 23, 2018 at 9:28am
Jul 23, 2018 at 2:14pm
1
2
3
4
for (int i = 0 ; i < pos -2 ; ++i)
        {
            temp2 = temp2 -> link; // temp 2 is already pointing at first node
        }


I corrected the loop and now i am facing another problem,if i input pos = 1 it removes the element at the first position and replaces instead of pushing it down! While my logic is aimed at the latter. ??

@repeater every thing is working except for pos = 1;
Last edited on Jul 23, 2018 at 4:19pm
Jul 23, 2018 at 4:22pm
Actually i was missing return statement there,everything resolved! Cheers.
Jul 24, 2018 at 3:48pm
In general you likely want to use zero-based indexing to not confuse everyone.

example with string data for clarity:
Data:    blah -> foo -> bar -> test -> hooray
Pos:       0      1      2       3       4


Typically an insert means you insert before a specified position. So if user entered "0", the new data would be inserted at the start, before "blah".

The spacing throughout the program could also be improved to reduce confusion. At first glance "pos -2" makes one think something is happening with a negative two.
Similarly, temp2->link is more clear at a glance than temp2 -> link -- the first way better shows an association.
Last edited on Jul 24, 2018 at 3:50pm
Jul 24, 2018 at 4:44pm
Actually I've been always indexing linked lists from 1 since i started but I will look into your suggestion and yes i know i about that spacing,i don't do it anymore now as many others also pointed out thank you very much.
Topic archived. No new replies allowed.