0% found this document useful (0 votes)
20 views

Copy SLL Examples

The document describes four copy constructors for a single linked list that copy nodes in different ways: copying all elements, copying alternate elements, copying even elements, and copying odd elements.

Uploaded by

noorjafffer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Copy SLL Examples

The document describes four copy constructors for a single linked list that copy nodes in different ways: copying all elements, copying alternate elements, copying even elements, and copying odd elements.

Uploaded by

noorjafffer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

**copy constructor ( copy all elements)

public SingleLinkedList(SingleLinkedList<E>l1){
if (l1.head==null){head=null;size=0; return;}
Node<E> ptr=l1.head;
Node<E> nptr=new Node<E>(ptr.data);
head=nptr;
ptr=ptr.next;
while (ptr!=null) {
Node<E> temp=new Node<E>(ptr.data);
nptr.next=temp;
nptr=temp;
ptr=ptr.next; } //end of while
size= l1.size();
}

** copy constructor ( copy alternate) copy node and skip the next
one
public SingleLinkedList(SingleLinkedList<E>l1){
if (l1.head==null){head=null;size=0; return;}
Node<E> ptr=l1.head;
Node<E> nptr=new Node<E>(ptr.data);
head=nptr;
size++;
ptr=ptr.next;
if (ptr!=null)
ptr=ptr.next;
while (ptr!=null){
Node<E> temp=new Node<E>(ptr.data);
nptr.next=temp;
nptr=temp;
size++;
ptr=ptr.next;
if (ptr!=null)
ptr=ptr.next;
}

** copy constructor ( copy even )


public SingleLinkedList(SingleLinkedList<E>l1){
if (l1.head==null){head=null;size=0; return;}
Node<E> ptr=l1.head;
while ((int)ptr.data%2!=0)
ptr=ptr.next;
Node<E>nptr=new Node<E>(ptr.data);
head=nptr;
size++;
ptr=ptr.next;
while (ptr!=null){
if ((int)ptr.data%2==0){
Node<E> temp=new Node<E>(ptr.data);
nptr.next=temp;
nptr=temp;
size++;
ptr=ptr.next;}
else ptr=ptr.next;
}

** copy constructor ( copy odd )


public SingleLinkedList(SingleLinkedList<E>l1){
if (l1.head==null){head=null;size=0; return;}
Node<E> ptr=l1.head;
while ((int)ptr.data%2!=1)
ptr=ptr.next;
Node<E>nptr=new Node<E>(ptr.data);
head=nptr;
size++;
ptr=ptr.next;
while (ptr!=null){
if ((int)ptr.data%2==1){
Node<E> temp=new Node<E>(ptr.data);
nptr.next=temp;
nptr=temp;
size++;
ptr=ptr.next;}
else ptr=ptr.next;
}

You might also like