Tuesday, 7 February 2017

Linked List insertion at the end and print

Linked List Implementation using pointers..



#include <iostream>

using namespace std;

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

void Insert_linkedlist(Node** start, int x)
{
Node * temp = new Node();
temp->data = x;
temp->next = NULL;
if (*start != NULL)
{
Node *ptr = *start;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = temp;
}
else
{
*start = temp;
}

}

void print_linkedlist(Node* start)
{
while (start != NULL)
{
cout << start->data << endl;
start = start->next;
}
}

int main()
{
Node* start = new Node();
    start = NULL;
int n, p;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> p;
Insert_linkedlist(&start, p);
}

print_linkedlist(start);

return 0;
}

No comments:

Post a Comment