Implement insertion of node at the end of list in singly linked list in C++
Code
#include <iostream>using namespace std;class Node{public:int data;Node *next;};void insertend(Node **head, int data){Node *newnode = new Node();newnode->data = data;newnode->next = NULL;if (*head == NULL){*head = newnode;return;}Node *last = *head;while (last->next != NULL){last = last->next;}last->next = newnode;}void printlist(Node *head){while (head != NULL){cout << head->data << " ";head = head->next;}}int main(){Node *head = NULL;insertend(&head, 1);insertend(&head, 2);insertend(&head, 3);insertend(&head, 4);insertend(&head, 5);printlist(head);return 0;}
Output
1 2 3 4 5
0 Comments
Post a Comment