Different methods to initialize a Linked List
#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node* next;
Node(
int
x)
{
data = x;
next = NULL;
}
};
class
linkedlist {
private
:
Node* head = NULL;
Node* tail = NULL;
public
:
linkedlist() { head = tail = NULL; }
linkedlist(
const
linkedlist& list)
{
if
(list.head == NULL) {
head = tail = NULL;
return
;
}
Node* temp = list.head;
while
(temp != NULL) {
Node* newNode =
new
Node(temp->data);
if
(head == NULL) {
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
temp = temp->next;
}
}
void
insert(
int
x)
{
Node* temp =
new
Node(x);
if
(head == NULL) {
head = temp;
return
;
}
else
{
Node* t = head;
while
(t->next != NULL) {
t = t->next;
}
t->next = temp;
}
}
void
print()
{
if
(head == NULL) {
cout <<
"List is empty"
<< endl;
return
;
}
Node* temp = head;
while
(temp != NULL) {
cout << temp->data <<
" "
;
temp = temp->next;
}
cout << endl;
}
};
int
main()
{
linkedlist l1;
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
cout <<
"linked list l1 are: "
;
l1.print();
linkedlist l2 = l1;
cout <<
"linked list l2 are: "
;
l2.print();
return
0;
}
#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node* next;
Node(
int
x)
{
data = x;
next = NULL;
}
};
class
linkedlist {
private
:
Node* head = NULL;
Node* tail = NULL;
public
:
linkedlist() { head = tail = NULL; }
linkedlist(
const
linkedlist& list)
{
if
(list.head == NULL) {
head = tail = NULL;
return
;
}
Node* temp = list.head;
while
(temp != NULL) {
Node* newNode =
new
Node(temp->data);
if
(head == NULL) {
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
temp = temp->next;
}
}
void
insert(
int
x)
{
Node* temp =
new
Node(x);
if
(head == NULL) {
head = temp;
return
;
}
else
{
Node* t = head;
while
(t->next != NULL) {
t = t->next;
}
t->next = temp;
}
}
void
print()
{
if
(head == NULL) {
cout <<
"List is empty"
<< endl;
return
;
}
Node* temp = head;
while
(temp != NULL) {
cout << temp->data <<
" "
;
temp = temp->next;
}
cout << endl;
}
};
int
main()
{
linkedlist l1;
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
cout <<
"linked list l1 are: "
;
l1.print();
linkedlist l2 = l1;
cout <<
"linked list l2 are: "
;
l2.print();
return
0;
}