Insert Node
Apr 4, 2015 at 6:20am UTC
I want to insert a node 2,4,6, and 5 and it should be inputted that way but it outputs 5,6,4, and 2.
How to fix this?
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
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int data)
{
Node*temp = new Node();
temp->data = data;
temp->next = NULL;
if (head != NULL)
temp->next = head;
head = temp;
}
void Print()
{
Node* temp = head;
while (temp != NULL)
{
cout << temp->data << " " ;
temp = temp->next;
}
cout << endl;
}
void Delete(int n)
{
struct Node* temp1 = head;
if (n == 1)
{
head = temp1->next;
free(temp1);
return ;
}
for (int i = 0; i<n - 2; i++)
temp1 = temp1->next;
struct Node* temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);//free the memory & deletes temp2;
}
int main()
{
head = NULL;
Insert(2);
Insert(4);
Insert(6);
Insert(5);
Print();
int n;
cout << "Enter a position: " ;
cin >> n;
Delete(n);
Print();
}
Apr 4, 2015 at 9:12am UTC
To insert at the end of a singly linked list you have 2 options (that I know of).
1) Iterate through the list each time to find the last node (tail) then:
last->next = temp;
2) Maintain a pointer to the last node, in addition to the pointer to the 1st node (head) which you already have. Code is 2 lines then:
1 2
tail->next = temp;// extending the list
tail = temp;// marking new end of list
Assign both = temp when creating the 1st node in the list:
1 2 3 4
if ( tail == NULL )
head = tail = temp;
else
// 1st code snippet
Apr 6, 2015 at 10:35am UTC
Like this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void Insert(int data)
{
Node*temp = new Node();
tail->next = temp;
tail = temp;
if (tail == NULL)
head = tail = temp;
else
{
temp->data = data;
temp->next = NULL;
if (head != NULL)
temp->next = head;
head = temp;
}
}
Apr 6, 2015 at 10:39am UTC
I fixed it! Thank you!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void Insert(int data)
{
Node*temp = new Node();
temp->data = data;
temp->next = NULL;
if (!head) {
head = temp;
return ;
}
else {
Node* tail = head;
while (tail->next) tail = tail->next;
tail->next = temp;
}
}
Topic archived. No new replies allowed.