Reputation: 58
I've been learning Data Structures and currently working with Linked List. I'm trying to add a node at the end of the linked list but not able to figure out the correct logic for it. I've tried inserting a node at the beginning and it works fine.
This is the code:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};
Node* head; // global
void Insert(int data) {
Node* temp = new Node();
temp -> data = data;
temp -> next = head;
head = temp;
} // insert an integer
void Print(){
Node* temp = head;
cout << "List is: ";
while (temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
cout << endl;
} // print all elements in the list
void Delete(int n){
Node* temp1 = head;
if(n == 1) {
head = temp1 -> next; // head now points to second node
delete temp1;
return;
}
int i;
for(i = 0; i < n-2; i++)
temp1 = temp1 -> next;
// temp1 points to (n-1)th Node
Node* temp2 = temp1 -> next; // nth Node
temp1 -> next = temp2 -> next; // (n+1)th Node
delete temp2; // delete temp2
} // Delete node at position n
int main() {
head = NULL; // empty list
Insert(2);
Insert(4);
Insert(6);
Insert(5); // List: 2,4,6,5
Print();
int n;
cout << "Enter a postion: " << endl;
cin >> n;
Delete(n);
Print();
}
This code deletes a node at nth position. The node here is being adding from the beginning and I'm trying to figure out the logic to insert it from the end.
Any suggestions and advises on this will be very helpful.
Thanking you in advance.
Upvotes: 2
Views: 675
Reputation: 8497
void insert_end(int data) {
Node* temp = new Node(); // 1
temp->data = data;
temp -> next = nullptr;
Node* n = head;
if (!n) { // 2
head = temp;
return;
}
while(n->next) { // 3
n = n->next;
}
n->next = temp;
}
Short explanation of the method:
1:
You create a new Node
and set the data.
2:
Check if the list is empty. If it is, insert the new element at the head.
3:
If the list is not empty, you read the next element of the list until you have the last Node in your list. If you would write while(n)...
here, you would get to the end of the list, meaning a nullptr
and the code would break.
Upvotes: 3